【问题标题】:Excel macro to compare two ranges for perfect matchExcel 宏比较两个范围以实现完美匹配
【发布时间】: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 一次来更改该代码以执行列。

标签: vba excel


【解决方案1】:

试试这个:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-31
    • 2017-07-02
    • 1970-01-01
    • 2011-12-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多