Как сравнить два значения диапазона для равенства в VBA Excel? - PullRequest
0 голосов
/ 15 декабря 2018

Ниже приведен мой код

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 голосов
/ 17 декабря 2018
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
0 голосов
/ 15 декабря 2018

Вы должны проверить каждый элемент

следующим образом (вы можете добавить некоторые проверки, чтобы убедиться, что размеры массивов одинаковы):

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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...