如何在VBA Excel中比较两个范围值是否相等?

时间:2018-12-15 10:09:30

标签: excel vba excel-vba

以下是我的代码

Data = wb.Worksheets(1).Range("B3:E6").Value
targetValue = ActiveSheet.Range(targetcellL, targetcellR).Value

If Data = targetValue Then
     MsgBox "Match Found"

End If

if条件给我错误“运行时错误13类型不匹配” 如何比较两个范围值?

2 个答案:

答案 0 :(得分:2)

您必须检查所有项目

如下(您可能要添加一些检查以确保数组大小相同):

Data = wb.Worksheets(1).Range("B3:E6").Value
targetValue = ActiveSheet.Range(targetcellL, targetcellR).Value

Dim i As Long, j As Long
Dim match As Boolean
match = True
For i = LBound(Data,1) to UBound(Data,1)
    For j = LBound(Data,2) to UBound(Data,2)    
        If Data(i, j) <> targetValue(i, j) Then
            match = False
            Exit For
        End If
    Next
    if Not match Then Exit For
Next
If match Then MsgBox "Match Found"

关于您似乎想要的“短途旅行” ,您可以考虑使用辅助程序Function()

Data = wb.Worksheets(1).Range("B3:E6").Value
targetValue = ActiveSheet.Range(targetcellL, targetcellR).Value

If DoArraysMatch(Data, targetValue) Then MsgBox "Match Found"

这是heleper DoArraysMatch()函数:

Function DoArraysMatch(arr1 As variant, arr2 As Variant) As Boolean
    Dim i As Long, j As Long
    Dim match As Boolean

    match = True
    For i = LBound(arr1,1) to UBound(arr1,1)
        For j = LBound(arr1,2) to UBound(arr1,2)    
            If arr1(i, j) <> arr2(i, j) Then
                match = False
                Exit For
            End If
        Next
        if Not match Then Exit For
    Next
    DoArraysMatch = match
End Function

答案 1 :(得分:0)

Function ArraysEqual() As Boolean
    Dim cell As Range, rng1 As Range, rng2 As Range
    ArraysEqual = True
    For Each cell In rng1
        If WorksheetFunction.CountIf(rng2, cell.Value) = 0 Then
            ArraysEqual = False
            Exit Function
        End If
    Next
End Function