使用本机代码中的值列表填充 VBA 数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28610988/
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
Populate VBA Array with list of values in native code
提问by JSS
Hoping there is a quick answer to this question....
希望这个问题有一个快速的答案......
I have an array and I want to populate it with a list of arguments.
我有一个数组,我想用参数列表填充它。
Sub EasyArrayInput()
Dim myArr() as variant
myArr = ("string1", "string2", "string3")
End Sub
I am well aware of how to loop through and populate with a for/next or do/while, but it would be nice to be able to populate an array when the values wont change without using a hardcoded method.
我很清楚如何使用 for/next 或 do/while 进行循环和填充,但是如果不使用硬编码方法而不会更改值,那么能够填充数组会很好。
Sub UsualMethodThatIDontWantToDo()
Dim myArr(1 to 3) as variant
myArr(1) = "string1"
myArr(2) = "string2"
myArr(3) = "string3"
End Sub
Is there anyway to do it in a method similar to the first code snippet? I would prefer to do it that way. I apologize if this question has been asked/answered, but I'm not quite sure what the method I am asking about is called.
有没有办法在类似于第一个代码片段的方法中做到这一点?我更愿意这样做。如果有人问/回答过这个问题,我深表歉意,但我不太确定我问的方法是什么。
Thanks in advance!
提前致谢!
Edit: Solution
编辑:解决方案
The code snippet below (from the link that chancea sent) will create an array that is a variant and exaclty what I wanted.
下面的代码片段(来自机会发送的链接)将创建一个数组,该数组是我想要的变体和精确的。
Sub EasyArrayInput()
Dim myArr() as variant
myArr = Array("string1", "string2", "string3")
End Sub
The next code snippet looks to be useful for if you only have strings and don't want to initialize a variant:
如果您只有字符串并且不想初始化变体,则下一个代码片段看起来很有用:
Sub EasyArrayInput()
Dim myArr() as String
myArr = Split("String1,String2,String3", ",")
End Sub
回答by user3561813
How about?
怎么样?
Sub EasyArrayInput()
Dim myArr() As Variant
myArr = Array("string1", "string2", "string3")
End Sub
回答by Rory
Assuming you have some sort of numeric sequence, you can do something like this:
假设您有某种数字序列,您可以执行以下操作:
Dim myArray()
myArray = [TRANSPOSE(INDEX("string"&ROW(1:10),))]
but frankly I think a loop is clearer.
但坦率地说,我认为循环更清晰。

