vba Microsoft Visual Basic:如何初始化数组变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18828139/
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
Microsoft Visual Basic: how to initialize an array variable?
提问by Carl Witthoft
I wrote a macro which performs certain operations on every instance of a specific set of Word Styles within a document.
我编写了一个宏,它对文档中一组特定 Word 样式的每个实例执行某些操作。
To do so, I created an array of names this way:
为此,我以这种方式创建了一个名称数组:
Dim mylist(4) As String
mylist(1) = "Heading 1"
mylist(2) = "Heading 2"
mylist(3) = "Heading 3"
mylist(4) = "Caption"
I was unable to find any help pages (inside Office Help or at microsoft.com) which mentioned a shorter way to do so. Is there any syntax that would let me simplify this into something like (pseudocode)
我找不到任何提到更短方法的帮助页面(在 Office 帮助内或在 microsoft.com 上)。是否有任何语法可以让我将其简化为类似(伪代码)
mylist(1:4) = ["Heading 1", "Heading 2", "Heading 3", "Caption"]
I'm looking for a general solution for one-line loading of an array, whether it's strings or numbers, when I don't want the entire collection of something like, say allstyles in a document.
我正在寻找一种单行加载数组的通用解决方案,无论是字符串还是数字,当我不想要整个集合之类的东西时,比如文档中的所有样式。
EDIT: I ran across Collection initialization syntax in Visual Basic 2008?, which suggests the answer is "not until VB10" . Any updates to that conclusion would be welcome.
编辑:我在 Visual Basic 2008 中遇到了集合初始化语法?,这表明答案是“直到 VB10”。欢迎对该结论进行任何更新。
回答by Derek
This is close but a little different than: Dim mylist(4) As String
这很接近,但与以下内容略有不同: Dim mylist(4) As String
Dim myarray As Variant
myarray = Array("Cat", "Dog", "Rabbit")
From: http://www.mrexcel.com/forum/excel-questions/18225-initializing-arrays-single-statement.html
来自:http: //www.mrexcel.com/forum/excel-questions/18225-initializing-arrays-single-statement.html
回答by EEM
If memory is not a problem (so data type can be variant) this generates a base 1 array
如果内存不是问题(所以数据类型可以是变体),这将生成一个基数为 1 的数组
Dim mylist As Variant
mylist = [{"Heading 1", "Heading 2", "Heading 3", "Caption"}]