我试图在VBA Excel中比较两个2d数组。
来源:
1 2 3 4
4 5 6 2
3 3 4 4
:定位:
4 5 3 2
1 2 3 4
3 7 7 5
鉴于以上两个2-d数组,我将其称为源和目标,我想比较源中的每一行与整个目标,并检查它是否存在于目标中。对于 来自源(1 2 3 4)的示例行1将被视为匹配,因为它将在目标中找到(在第2行)。所以我需要比较源中给定行的目标中的每一行。如果目标中不存在源代码行,那么我需要记下一些如何标记为不存在于目标中。
有些东西(不是实际代码只是想法):
For i to ubound(srcArray)
isFound = False
For j To ubound(trgArray)
If srcArray(i) = trgArray(j) Then
isFound = True
If Not isFound Then
//make note of some sort
我知道方法适用于单身昏暗。阵列。但是尝试在VB或其他方法中的某种循环中为2d数组执行此操作。不熟悉Excel中的VB。如果可能的话,我还想将每一行看作整个数组,而不是单独比较每个数组的每个元素。
答案 0 :(得分:2)
以下是如何循环和比较2D数组元素的示例:
Sub ArrayCompare()
Dim MyArr1 As Variant, MyArr2 As Variant, X as long, Y as long
MyArr1 = [{1,2,3,4;4,5,6,2;3,3,4,4}]: MyArr2 = [{4,5,3,2;1,2,3,4;3,7,7,5}]
For X = LBound(MyArr1) To UBound(MyArr1)
For Y = LBound(MyArr1, 1) To UBound(MyArr1, 1)
If MyArr1(X, Y) = MyArr2(X, Y) Then MsgBox X & ":" & Y & ":" & MyArr1(X, Y)
Next
Next
End Sub
这是我更新的代码,用于将每一行比较为字符串(Thanks @Tim Williams :)):
Sub ArrayCompare()
Dim MyArr1 As Variant, MyArr2 As Variant, X As Long, Y As Long
MyArr1 = [{1,2,3,4;4,5,6,2;3,3,4,4}]: MyArr2 = [{4,5,3,2;1,2,3,4;3,7,7,5}]
For X = LBound(MyArr1) To UBound(MyArr1)
For Y = LBound(MyArr2) To UBound(MyArr2)
If Join(Application.Transpose(Application.Transpose(Application.Index(MyArr1, X, 0))), "|") = Join(Application.Transpose(Application.Transpose(Application.Index(MyArr2, Y, 0))), "|") Then MsgBox "Found a match at MyArr1 index:" & X & " and MyArr2 index:" & Y
Next
Next
End Sub
答案 1 :(得分:2)
如果你真的想避免循环,那么你使用这种方法从你的二维数组中提取一个“行”以进行比较,但循环可能会更快。
Sub Tester()
Dim arr, rw
arr = Range("A1:J10").Value 'get 2-d array from worksheet
'get a 1-d array "row" out of the 2-d array
rw = Application.Transpose( _
Application.Transpose(Application.Index(arr, 1, 0)))
'then you can (eg) create a string for comparison purposes
Debug.Print Join(rw, Chr(0))
End Sub