Excelmacros比较两个范围完美匹配

当我运行macros时,如果L6:L29的值匹配,按行排列,则M6:M29中的值会popup消息。

写这个的长而低效的方法可能是:

Public Sub MyMacro() If Range("L6").Value = Range("M6).Value AND Range("L7").Value = Range("M7).Value AND Range("L8").Value = Range("M8).Value etc. Then MsgBox "Both columns match!.", vbInformation, "Match!" Exit Sub End If ... End Sub 

但我正在寻找更有效的代码,可以评估两列/范围中的每一行,而无需指定每一对。

我也看到了类似的问题的下面的答案,但它只评估一行(在这种情况下,#5)。 我需要评估范围内的每一行: 最快的方法来检查在Excel VBA中两个范围是否相等

 Sub RowCompare() Dim ary1() As Variant Dim Range1 As Range, Range2 As Range, rr1 As Range, rr2 As Range Set Range1 = Range("B9:F20") Set Range2 = Range("I16:M27") Set rr1 = Range1.Rows(5) Set rr2 = Range2.Rows(5) ary1 = Application.Transpose(Application.Transpose(rr1)) ary2 = Application.Transpose(Application.Transpose(rr2)) st1 = Join(ary1, ",") st2 = Join(ary2, ",") If st1 = st2 Then MsgBox "the same" Else MsgBox "different" End If End Sub 

尝试这个:

 Option Explicit 

 Sub RowCompare() Dim i As Long Dim ComparisionResult As Boolean For i = 6 To 29 If IIf(Cells(i, 12).Value = "", "", Cells(i, 12).Value) = IIf(Cells(i, 13).Value = "", "", Cells(i, 13).Value) Then ComparisionResult = True Else ComparisionResult = False Exit For End If Next i If ComparisionResult Then MsgBox "Both columns match!", vbInformation, "Match!" Else _ MsgBox "different", vbInformation, "Match!" End Sub