3

我正在尝试比较来自两个范围的数据。“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
4

3 回答 3

3

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

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

在此处输入图像描述

菲利普

于 2013-04-25T23:42:33.230 回答
2

这是一个非常小的范围,但我仍然建议使用数组来存储您的范围值,然后使用数组进行比较。请参阅此示例。

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

在此处输入图像描述

编辑

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

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
于 2013-04-25T23:08:59.080 回答
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
于 2013-04-26T01:29:11.767 回答