3

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.

Community
  • 1
  • 1
Carl Witthoft
  • 20,573
  • 9
  • 43
  • 73

2 Answers2

6

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

Derek
  • 7,615
  • 5
  • 33
  • 58
  • This will use more memory though. If you only want to use it for strings, stay with String type – makciook Sep 16 '13 at 12:38
  • I don't have any huge lists, so memory not a problem. So long as it works for `Word` as well as `Excel` I should be OK. I'll report back. – Carl Witthoft Sep 16 '13 at 12:41
  • That link also suggested `Dim mylist() As String mylist = Split("Heading 1,Heading 2,Caption", ",")` . Both options work fine, other than that I have to remember that these arrays' index starts at zero, not one. Thanks! – Carl Witthoft Sep 16 '13 at 12:53
  • 1
    Split("Ignore me,Heading 1, Heading 2 ...") and you can pretend that the array is 1-based. ;-) – Steve Rindsberg Sep 16 '13 at 13:57
1

If memory is not a problem (so data type can be variant) this generates a base 1 array

Dim mylist As Variant
    mylist = [{"Heading 1", "Heading 2", "Heading 3", "Caption"}]
EEM
  • 6,601
  • 2
  • 18
  • 33