比较三个动态范围

时间:2018-11-29 19:47:50

标签: excel vba

我正在尝试比较Workbooks的pkws(A列),tmpws(A列)和fdws(B列)。

数据看起来像“ 123456789”。如果匹配,则宏应在pkws工作簿中突出显示一行。

这是我的代码,适用于两个工作簿,但不适用于三个工作簿。我尝试输入另一个变量(比较pkws和fdws)。

If StrComp(Trim(range1.Text), Trim(range2.Text), vbTextCompare) = 0 Then
Dim range1 As Range, range2 As Range, n As Long, m As Long
For n = 1 To pkws.Range("A" & Rows.count).End(xlUp).Row
    Set range1 = pkws.Range("A" & n)
    For m = 1 To tmpws.Range("A" & Rows.count).End(xlUp).Row
        Set range2 = tmpws.Range("A" & m)
        If StrComp(Trim(range1.Text), Trim(range2.Text), vbTextCompare) = 0 Then
            range1.Interior.Color = RGB(255, 255, 0)
        End If
        Set range2 = Nothing
    Next m
    Set range1 = Nothing
Next n

1 个答案:

答案 0 :(得分:0)

您的嵌套循环方法将非常慢,因此类似这样的方法可能会更好:

Sub Tester()

    Dim range1 As Range, range2 As Range, range3 As Range, c As Range
    Dim m1, m2, v

    Set range1 = pkws.Range("A1:A" & pkws.Cells(Rows.Count, 1).End(xlUp).Row)
    Set range2 = tmpws.Range("A1:A" & tmpws.Cells(Rows.Count, 1).End(xlUp).Row)
    Set range3 = fdws.Range("A1:A" & fdws.Cells(Rows.Count, 1).End(xlUp).Row) '<<EDIT

    For Each c In range1.Cells
        v = c.Text
        'look for matches in the other sheets
        m1 = Application.Match(v, range2, 0)
        m2 = Application.Match(v, range3, 0)

        If Not IsError(m1) And Not IsError(m2) Then
            'got two matches...
            c.Interior.Color = RGB(255, 255, 0)
        End If
    Next c

End Sub