一個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
使用這個自定義函數的示例:
=CompareRanges(A1:A10, B1:B10, C1)
其中,A1:A10是源範圍,B1:B10是目標範圍,C1是比對條件。按下Enter鍵,函數將計算並返回符合比對條件的數量。
這個示例中,我們創建了一個名為"CompareRanges"的自定義函數,它接受三個參數:源範圍、目標範圍和比對條件。根據比對條件,它將比對這兩個範圍的數據,並返回符合條件的數量。請確保在Excel中啟用了宏,以便使用這個自定義函數。