当我运行一个宏时,如果L6:L29的值匹配,行到行,M6:M29中的值,我想要弹出一条消息。
写这篇文章的长而低效的方法可能是:
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)。我需要评估范围中的每一行:Fastest way to check if two ranges are equal in 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
答案 0 :(得分:2)
试试这个:
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