Excel函數撰寫

閱讀時間約 3 分鐘

一個EXCEL比對函數

Excel VBA中創建一個自定義函數,用於比對兩個儲存格範圍的數據。這個示例函數將返回符合指定比對條件的數量。vba

Function CompareRanges(sourceRange As Range, targetRange As Range, criteria As String) As Long
Dim sourceCell As Range
Dim targetCell As Range
Dim countMatches As Long

countMatches = 0

' 檢查比對條件是否合法
If criteria <> "=" And criteria <> "<" And criteria <> ">" Then
CompareRanges = CVErr(xlErrValue) ' 返回錯誤值
Exit Function
End If

' 開始比對
For Each sourceCell In sourceRange
For Each targetCell In targetRange
If criteria = "=" And sourceCell.Value = targetCell.Value Then
countMatches = countMatches + 1
ElseIf criteria = "<" And sourceCell.Value < targetCell.Value Then
countMatches = countMatches + 1
ElseIf criteria = ">" And sourceCell.Value > targetCell.Value Then
countMatches = countMatches + 1
End If
Next targetCell
Next sourceCell

CompareRanges = countMatches ' 返回符合比對條件的數量
End Function






使用這個自定義函數的示例:

  1. 打開Excel工作簿。
  2. 在一個儲存格中輸入比對條件,例如"="。
  3. 在另一個儲存格中輸入以下函數:=CompareRanges(A1:A10, B1:B10, C1)
  4. less
=CompareRanges(A1:A10, B1:B10, C1)


其中,A1:A10是源範圍,B1:B10是目標範圍,C1是比對條件。按下Enter鍵,函數將計算並返回符合比對條件的數量。

這個示例中,我們創建了一個名為"CompareRanges"的自定義函數,它接受三個參數:源範圍、目標範圍和比對條件。根據比對條件,它將比對這兩個範圍的數據,並返回符合條件的數量。請確保在Excel中啟用了宏,以便使用這個自定義函數。

    6會員
    98內容數
    編劇的一些想法及劇情探討
    留言0
    查看全部
    發表第一個留言支持創作者!
    你可能也想看
    Google News 追蹤
    Thumbnail
    本專欄將提供給您最新的市場資訊、產業研究、交易心法、精選公司介紹,以上內容並非個股分析,還請各位依據自身狀況作出交易決策。歡迎訂閱支持我,獲得相關內容,也祝您的投資之路順遂! 每年 $990 訂閱方案👉 https://reurl.cc/VNYVxZ 每月 $99 訂閱方案👉https://re
    Thumbnail
    本專欄將提供給您最新的市場資訊、產業研究、交易心法、精選公司介紹,以上內容並非個股分析,還請各位依據自身狀況作出交易決策。歡迎訂閱支持我,獲得相關內容,也祝您的投資之路順遂! 每年 $990 訂閱方案👉 https://reurl.cc/VNYVxZ 每月 $99 訂閱方案👉https://re