【发布时间】:2017-11-18 05:37:20
【问题描述】:
运行宏时,如果 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
但我正在寻找更高效的代码,它可以评估两列/范围中的每一行,而无需指定每一对。
我确实看到了类似问题的以下答案,但它只评估 one 行(在本例中为 #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
【问题讨论】:
-
您可以通过仅使用 Application.Transpose 一次来更改该代码以执行列。