Search code examples
vbainitialization

Microsoft Visual Basic: how to initialize an array variable?


I wrote a macro which performs certain operations on every instance of a specific set of Word Styles within a document.

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)

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 all styles 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.


Solution

  • This is close but a little different than: 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