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

Excel VBA-我的动态数组仅包含最后添加的值,vba,excel,dynamic-arrays,Vba,Excel,Dynamic Arrays,我正在尝试填充一个动态数组,它确实可以获得正确数量的值。 例如,它需要有3个值。它有3个值,但只有最后一个值是真实值 为了澄清这一点,以下是该阵列的外观: 数组,实际字符串值 所以前2个值是空的 我不知道我做错了什么。代码如下: Dim LinkSheet As Worksheet Set LinkSheet = ThisWorkbook.Sheets("Resources") Dim LinkNameRange As Range Set LinkNameRang

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

为了澄清这一点,以下是该阵列的外观: 数组,实际字符串值 所以前2个值是空的

我不知道我做错了什么。代码如下:

    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
甚至可能是我测试错了什么的。感谢您的帮助。
提前谢谢

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


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

您的范围是一列吗

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

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)
如果是交叉行,则需要像这样转置两次:

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

您需要在redim语句中使用preserve关键字来保留先前添加的值,这很可能是正确的答案。谢谢,我试试看!那当然行,我真蠢。。如果你愿意,你可以把它作为一个答案,我会接受的;