excel 比较2个阵列

suzh9iv8  于 2023-02-05  发布在  其他
关注(0)|答案(2)|浏览(113)

我正在Excel 2010的VBA中比较两个数组。下面是我的示例代码:

Dim vArray1 As Variant
Dim vArray2 As Variant

Set wb1 = ActiveWorkbook
Set myTable = wb1.Worksheets(3).ListObjects("Table3")

vArray1 = myTable.DataBodyRange
vArray2 = wb1.Worksheets(2).Range("B1:B" & lRow1).Value

k = 1

For i = LBound(vArray1) To UBound(vArray1)
   For j = LBound(vArray2) To UBound(vArray2)
      If vArray1(i, 1) = vArray2(j, 1) Then
         ' Do nothing
      Else
         vArray3(k, 1) = vArray1(i, 1)
         k = k + 1
      End If
   Next
Next

我想将表3中的第1列与vArray2中存储的范围进行比较。
vArray1中存在但vArray2中不存在的任何值都需要存储在vArray3中。很遗憾,我无法完成此操作。如有任何帮助,将不胜感激。

wlzqhblo

wlzqhblo1#

**Edit1:**我重写了你的循环,我认为这是问题的原因。UboundLbound 假设第一个维度,如果它没有被提供。所以你做它的方式和下面应该返回正确的上限和下限。但是当然,当你处理二维数组时,最好是显式的。而且 vArray3 应该是 Dimensioned。我在你的代码中没有看到它。还添加了一个 Boolean 变量。

ReDim vArray3 (1 to 10, 1 to 2) '~~> change to suit
Dim dup As Boolean: k = 1
For i = LBound(vArray1, 1) To UBound(vArray1, 1) '~~> specify dimension
    dup = False
    For j = LBound(vArray2, 1) To UBound(vArray2, 1) '~~> specify dimension
        If vArray1(i, 1) = vArray2(j, 1) Then
            dup = True: Exit For
        End If
    Next j
    If Not dup Then '~~> transfer if not duplicate
        vArray3(k, 1) = vArray1(i, 1)
        k = k + 1
    End If
Next I

也可以像这样使用match:

'~~> Use 1D array instead by using Transpose
vArray2 = Application.Transpose(wb1.Worksheets(2).Range("B1:B" & lRow1))
For i = LBound(vArray1, 1) To UBound(vArray1, 1) '~~> specify dimension
    If IsError(Application.Match(vArray1(i, 1), vArray2, 0)) Then
        vArray3(k, 1) = vArray1(i, 1)
        k = k + 1
    End If
Next i
xvw2m8pv

xvw2m8pv2#

If (Join(varArray1, ",") = Join(varArray2, ",")) Then
    IsEqual = True
End If

相关问题