如何在一个数组中创建另一个数组(VBA)中的值?

时间:2016-04-16 11:57:33

标签: arrays vba excel-vba if-statement excel

我想创建一段代码,让我可以将数组中的值分配给另一个不同长度的数组。这就是我到目前为止所拥有的。

A(1) = 0
A(2) = 0
A(3) = 6
A(4) = 5
A(5) = 7

n = 0

For i = 1 To 5
If A(i) <> 0 Then
    n = n + 1
End If
Next i

ReDim B(1 To n) As Integer
For j = 1 To n
    For i = 1 To 5
        If A(i) <> 0 Then
            B(j) = A(i)
        End If
    Next i
Next j

MsgBox B(2)

此时返回7而它应该返回5,B中的所有值都是7.如何才能运行此代码?

2 个答案:

答案 0 :(得分:2)

你有嵌套循环的事实会引起你的注意:这将被执行n * 5次,这是不正确的。

更改第二部分,使它只使用一个循环,如下所示:

ReDim B(1 To n) As Integer
j = 1
For i = 1 To UBound(A)
    If A(i) <> 0 Then
        B(j) = A(i)
        j = j + 1
    End If
Next i

另请注意,使用UBound代替5会使您的代码更具通用性。另请注意,此循环与计算n的循环非常相似。唯一的区别是您分配到B(j)

如果您要将B重新标记两次,那么您可以将其与第一个循环合并,第二次使用Preserve

ReDim B(1 To UBound(A)) As Integer
n = 0
For i = 1 To UBound(A)
    If A(i) <> 0 Then
        n = n + 1
        B(n) = A(i)
    End If
Next i
' Shorten the array without losing data:
ReDim Preserve B(1 To n)

答案 1 :(得分:0)

您将不得不检查B是否有第一个空数组元素并退出循环,因此您不会继续写入。

Dim A() As Variant, B() As Variant
Dim i As Long, j As Long, n As Long

A = Array(0, 0, 6, 5, 7)  '<~~ 0 to 4, not 1 to 5

n = 0
For i = LBound(A) To UBound(A)
    If A(i) <> 0 Then
        n = n + 1
    End If
Next i

ReDim B(1 To n) '<~~ 1 to 3

For i = LBound(A) To UBound(A)
    If A(i) <> 0 Then
        For j = LBound(B) To UBound(B)
            If IsEmpty(B(j)) Then
                B(j) = A(i) '<~~ assigned a value; exit loop
                Exit For
            End If
        Next j
    End If
Next i

For j = LBound(B) To UBound(B)
    Debug.Print B(j)
Next j

鉴于数组可以是从零开始的,也可以是从一开始的,我更喜欢使用published a podLBound函数来定义它们的范围。