带有循环VBA的multidimensional array

尝试检查第一列的值(即multidimensional array中的列),如果它匹配与该行匹配的值的另一列。

我认为我做错了,但这是我第一次搞乱multidimensional array。

我是否需要在每个循环中使用UBound和LBound来告诉它要查看哪个colum?

除了仅仅是当前问题的答案/解决scheme之外,我对于学习将来使用这种方法的最佳实践方法感兴趣。

码:

Private Sub ThisStuff() Dim CoaAmt As Long Dim COAArray(3, 2) Dim ThisValue As String Dim AnotherValue As String AnotherValue = "Bananas" ThisValue = "Apples" COAArray(0, 0) = "Apples" COAArray(1, 0) = "Oranges" COAArray(2, 0) = "Peaches" COAArray(3, 0) = "Pomegranets" COAArray(0, 1) = 498 COAArray(0, 1) = 505 COAArray(1, 1) = 564 COAArray(1, 2) = 556 COAArray(2, 1) = 570 COAArray(2, 2) = 573 COAArray(3, 1) = 742 COAArray(3, 2) = 750 If AnotherValue = "Bananas" Then For i = COAArray(0, 0) To COAArray(3, 0) For j = COAArray(1, 0) To COAArray(3, 2) If COAArray(i, j) = ThisValue Then CoaAmt = COAArray(i, j) Next j Next i End If MsgBox ("The value of CoaAmt is " & CoaAmt) End Sub 

是。 LBound和UBound函数允许你指定等级 。 这让你嵌套的For .. Next循环遍历所有的数组元素。

  debug.print LBound(COAArray, 1) & ":" & UBound(COAArray, 1) debug.print LBound(COAArray, 2) & ":" & UBound(COAArray, 2) If AnotherValue = "Bananas" Then For i = LBound(COAArray, 1) To UBound(COAArray, 1) For j = LBound(COAArray, 2) To UBound(COAArray, 2) If COAArray(i, j) = ThisValue Then CoaAmt = COAArray(i, j) Next j Next i End If 

你的数组元素分配有点搞砸了。 应该更接近,

 COAArray(0, 0) = "Apples" COAArray(1, 0) = "Oranges" COAArray(2, 0) = "Peaches" COAArray(3, 0) = "Pomegranates" COAArray(0, 1) = 498 COAArray(1, 1) = 505 COAArray(2, 1) = 564 COAArray(3, 1) = 556 COAArray(0, 2) = 570 COAArray(1, 2) = 573 COAArray(2, 2) = 742 COAArray(3, 2) = 750 

例如,对于上面修复的数组赋值,COAArray(0,0)是Apples,COAArray(0,1)是498,COAArray(0,2)是570.接下来吐出498和570。

  Dim i As Long, j As Long Dim COAArray(3, 2) As Variant, CoaAmt(0 To 1) As Variant Dim ThisValue As String, AnotherValue As String AnotherValue = "Bananas" ThisValue = "Apples" COAArray(0, 0) = "Apples" COAArray(1, 0) = "Oranges" COAArray(2, 0) = "Peaches" COAArray(3, 0) = "Pomegranets" COAArray(0, 1) = 498 COAArray(1, 1) = 505 COAArray(2, 1) = 564 COAArray(3, 1) = 556 COAArray(0, 2) = 570 COAArray(1, 2) = 573 COAArray(2, 2) = 742 COAArray(3, 2) = 750 If AnotherValue = "Bananas" Then For i = LBound(COAArray, 1) To UBound(COAArray, 1) If COAArray(i, 0) = ThisValue Then For j = LBound(COAArray, 2) + 1 To UBound(COAArray, 2) CoaAmt(j - 1) = COAArray(i, j) Next j End If Next i End If MsgBox "The value of CoaAmt is " & CoaAmt(LBound(CoaAmt)) & " " & CoaAmt(UBound(CoaAmt)) 

我不得不改变你的CoaAmt var到一个一维的变体数组,以便收集这两个数字并输出它们。