将值添加到变量数组 VBA
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12663879/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
adding values to variable array VBA
提问by Trung Tran
I am trying to loop through a table
that has a column
for "customers" and "dollar amount"
. If my loop finds a customer
called "greg" or "henry"
I want to add his "dollar amount"
to an array of an unknown size.
我正在尝试遍历table
具有column
for 的a "customers" and "dollar amount"
。如果我的循环找到一个customer
被调用的,"greg" or "henry"
我想将他的添加"dollar amount"
到一个未知大小的数组中。
Can someone please help me?
有人可以帮帮我吗?
回答by Steve Rindsberg
If by unknown size, you mean that number of elements is unknown, you could use a dynamic array.
如果未知大小意味着元素数量未知,则可以使用动态数组。
Dim aArray() As Single ' or whatever data type you wish to use
ReDim aArray(1 To 1) As Single
If strFirstName = "henry" Then
aArray(UBound(aArray)) = 123.45
ReDim Preserve aArray(1 To UBound(aArray) + 1) As Single
End If
Ubound(aArray) throws an error if the array hasn't been dimensioned, so we start by adding an element to it. That leaves us with an empty element at the end of the text, so your code should account for that. aArray(Ubound(aArray)-1) will give you the last valid element in the array.
Ubound(aArray) 会在数组没有被维度化的情况下抛出一个错误,所以我们首先向它添加一个元素。这在文本末尾留下了一个空元素,因此您的代码应该考虑到这一点。aArray(Ubound(aArray)-1) 将为您提供数组中的最后一个有效元素。
回答by Pawel
Private Sub ArrayMy(DataRange)
Dim DataIndex() As String
i = 0
On Error Resume Next
ReDim DataIndex(0)
For Each c In DataRange
DataIndex(i) = c
i = i + 1
ReDim Preserve DataIndex(i)
Next
End Sub