2014-09-30 194 views
-1

我试图填充一个动态数组,并且它在获取正确数量的值方面起作用。
例如,它需要有3个值,它有3个值,但只有最后一个就像一个实际值。Excel VBA - 我的动态数组只包含添加的最后一个值

要清除了,这一点,该数组会是什么样子:
Array("", "", "actual string value")
所以第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 

它甚至可能是,我测试它错了或什么的。任何帮助表示赞赏。
在此先感谢!

+1

你需要在你的redim语句中使用preserve关键字来保持之前添加的值 – Sorceri 2014-09-30 14:37:39

+0

这很可能是正确的答案。谢谢,我会尝试! – 2014-09-30 14:38:45

+0

当然,这是有效的,我多么愚蠢......如果你愿意,你可以把它作为答案,我会接受它;) – 2014-09-30 14:40:12

回答

3

您需要使用您的ReDim语句的保留关键字,以保持先前

添加保留值:关键字用来保存数据的现有阵列中,当你改变的最后一个维度的大小。

+0

这就是问题所在!我会尽快接受,必须等待10分钟.. – 2014-09-30 14:42:42

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 
相关问题