在 VBA 中动态追加数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14602814/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 14:50:21  来源:igfitidea点击:

Dynamically appending an array in VBA

arraysexcelvbaexcel-vba

提问by harryg

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 uboundor an lbound. When I dim it as myArr(0 to 0)this also fails.

显然这是一个例子,所以不是最优雅的放置方式,但它不起作用,因为我似乎无法重新调整数组,因为它最初没有 auboundlbound. 当我把它调暗时,myArr(0 to 0)这也失败了。

Any ideas?

有任何想法吗?

采纳答案by Olle Sj?gren

Before using the myArrarray the first time, run this:

myArr第一次使用数组之前,运行这个:

ReDim Preserve myArr(0 To 1)

Then when you come to the dynamic ReDimstatement, only use ReDimif certain conditions are met, e.g. If UBound(myArr) > 1 thenetc.

然后当你来到动态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

回答by ecoe

Olle's solution can be expanded upon with some more checks and balances, if it interests you.

如果您感兴趣,可以通过更多的制衡来扩展 Olle 的解决方案。

see the InsertElementIntoArrayFunction here: http://www.cpearson.com/excel/VBAArrays.htm

请参阅InsertElementIntoArray此处的功能:http: //www.cpearson.com/excel/VBAArrays.htm