在Excel中比较两个范围

时间:2013-04-25 22:58:57

标签: excel excel-vba vba

我正在尝试比较两个范围的数据。 “A”含有1,2,3,4,“B”含有1,2,5。我想找到那些在“B”但不在“A”中的那些,这是5.下面是我的代码,但我似乎无法得到我想要的东西。有人可以建议吗?

Dim a As Range, b As Range, i As Integer, x As Integer
Set a = Range("A1:A4")
Set b = Range("B1:B3")

For i = 1 To b.Count
  For x = 1 To a.Count

    If b(i, 1) = a(x, 1) Then

    Else
      MsgBox (b(i, 1))
      Exit For
    End If
  Next x
Next i

3 个答案:

答案 0 :(得分:3)

或者,如果您想要使用Excel工作表函数的非VBA解决方案,请在列C列中尝试此公式

=IF(ISERROR(FIND(B:B,A:A)),B:B&" is not found","")

enter image description here

菲利普

答案 1 :(得分:2)

这是一个非常小的范围,但我仍然建议使用Arrays存储您的范围值,然后使用数组进行比较。见这个例子。

Sub Sample()
    Dim Ar1, Ar2
    Dim i As Long, j As Long
    Dim Found As Boolean

    Ar1 = Range("A1:A4"): Ar2 = Range("B1:B3")

    For i = LBound(Ar2) To UBound(Ar2)
        Found = False
        For j = LBound(Ar1) To UBound(Ar1)
            If Ar1(j, 1) = Ar2(i, 1) Then
                Found = True
                Exit For
            End If
        Next j

        If Found = False Then Debug.Print Ar2(i, 1) & " Is unique"
    Next i
End Sub

enter image description here

修改

另一种方式(我仍然喜欢上述方式

Sub Sample()
    Dim rngA As Range, rngB As Range
    Dim aCell As Range, bCell As Range
    Dim Found As Boolean

    Set rngA = Range("A1:A4"): Set rngB = Range("B1:B3")

    For Each aCell In rngB
        Found = False
        For Each bCell In rngA
            If bCell.Value = aCell.Value Then
                Found = True
                Exit For
            End If
        Next

        If Found = False Then Debug.Print aCell.Value & " Is unique"
    Next
End Sub

答案 2 :(得分:1)

我倾向于喜欢像Find()这样的原生VBA函数。我发现它们使用起来要快一些,特别是当你在大范围工作时。

这是另一种解决方案:

Option Explicit
Sub test()
    Dim r1 As Excel.Range
    Dim r2 As Excel.Range

    Set r1 = Sheet1.Range("A1:A4")
    Set r2 = Sheet1.Range("B1:B3")

    Dim s() As String

    s = getUniques(r1, r2)

    Dim i As Long
    For i = 0 To UBound(s)
        Debug.Print s(i)
    Next i
End Sub


Function getUniques(ByRef r1 As Excel.Range, ByRef r2 As Excel.Range) As String()
    Dim cell As Excel.Range
    Dim found As Excel.Range

    Dim uniques() As String
    Dim i As Long

    For Each cell In r2
        On Error Resume Next
        Set found = r1.Find(cell.Value)
        On Error GoTo 0

        If (found Is Nothing) Then
            ReDim Preserve uniques(i)
            uniques(i) = cell.Value
            i = i + 1
        End If
    Next cell

    getUniques = uniques
End Function