Excel VBA - 我的动态数组仅包含添加的最后一个值

时间:2014-09-30 14:36:54

标签: excel vba excel-vba dynamic-arrays

我正在尝试填充动态数组,它确实可以获得正确的数值。
例如,它需要有3个值,它有3个值,但只有最后一个像真实值。

要清除它,这就是那个阵列的样子:
Array("", "", "actual string value")
所以前两个值是空的。

我无法弄清楚我做错了什么。这是代码:

    Dim LinkSheet As Worksheet
    Set LinkSheet = ThisWorkbook.Sheets("Resources")
    Dim LinkNameRange As Range
    Set LinkNameRange = LinkSheet.Range("Table4[Resource Name]")

    Dim i As Integer
    Dim PlannedProjArr() As String
    i = 0

   'loop through all links and find the projects that the chosen employee is linked to

    For Each linkname In LinkNameRange
        If linkname = Employee Then
            ReDim PlannedProjArr(i)
            PlannedProjArr(i) = linkname.Offset(, -1).Value
            i = i + 1
        End If
    Next linkname

    'test if array works
    For x = 0 To UBound(PlannedProjArr)
        Debug.Print PlannedProjArr(x)
    Next x

甚至可能是我测试错了什么的。任何帮助表示赞赏 提前谢谢!

2 个答案:

答案 0 :(得分:3)

您需要在redim语句中使用preserve关键字来保留之前添加的值

保留:当您更改最后一个维度的大小时,用于保留现有数组中数据的关键字。

答案 1 :(得分:0)

你的范围是一列吗?

如果是这样,您可以在不循环的情况下进行填充,并自动设置数组的大小,如下所示:

Sub testArray()
'Dim the array
Dim MyArr As Variant
'Set the Array to be the values of the range. We use transpose to change the orientation from columns going down to an array which goes accross
MyArr = Application.Transpose(Range("M1:M4"))
'Join the Array and display it for testing
MsgBox Join(MyArr, " - ")
End Sub

在你的情况下,它会是这样的:

PlannedProjArr = Application.Transpose(LinkNameRange)

如果它是跨越行,那么你需要像这样转置TWICE:

Sub testArray()
'Dim the array
Dim MyArr As Variant
'Set the Array to be the values of the range. We use double transpose to change the orientation from rows to columns then back
MyArr = Application.Transpose(Application.Transpose(Range("M1:O1")))
'Join the Array and display it for testing
MsgBox Join(MyArr, " - ")
End Sub