[英]Dynamically appending an array in VBA
I want to append an array with a number depending on the condition of various variables. 我想根据各种变量的条件追加一个带数字的数组。 Here is the code I've come up with: I begin with an empty array.
这是我提出的代码:我从一个空数组开始。
Sub makeArr()
Dim myArr() As Integer
If box1 = True Then
ReDim Preserve myArr(LBound(myArr) To UBound(myArr) + 1)
myArr(UBound(myArr)) = 1
End If
If box2 = True Then
ReDim Preserve myArr(LBound(myArr) To UBound(myArr) + 1)
myArr(UBound(myArr)) = 2
End If
End Sub
Obviously this is an example so not the most elegant way of putting it but it doesn't work as I can't seem to reDim the array as it doesn't initially have a ubound
or an lbound
. 显然这是一个例子,所以不是最优雅的方式,但它不起作用,因为我似乎无法重新调整数组,因为它最初没有
ubound
或lbound
。 When I dim it as myArr(0 to 0)
this also fails. 当我将其
myArr(0 to 0)
暗为myArr(0 to 0)
这也会失败。
Any ideas? 有任何想法吗?
Before using the myArr
array the first time, run this: 在第一次使用
myArr
数组之前,运行以下命令:
ReDim Preserve myArr(0 To 1)
Then when you come to the dynamic ReDim
statement, only use ReDim
if certain conditions are met, eg If UBound(myArr) > 1 then
etc. 然后,当您进入动态
ReDim
语句时,仅在满足某些条件时才使用ReDim
,例如, If UBound(myArr) > 1 then
等。
If box1 = True Then
If UBound(myArr) > 1 Then
ReDim Preserve myArr(LBound(myArr) To UBound(myArr) + 1)
End If
myArr(UBound(myArr)) = 1
End If
Olle's solution can be expanded upon with some more checks and balances, if it interests you. 如果感兴趣的话,Olle的解决方案可以通过更多的检查和平衡来扩展。
see the InsertElementIntoArray
Function here: http://www.cpearson.com/excel/VBAArrays.htm 请参阅此处的
InsertElementIntoArray
函数: http : InsertElementIntoArray
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.