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.

1
  • We all secretly wish VB was more like FORTRAN. Commented Sep 16, 2013 at 12:59

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

5 Comments

This will use more memory though. If you only want to use it for strings, stay with String type
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.
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!
Split("Ignore me,Heading 1, Heading 2 ...") and you can pretend that the array is 1-based. ;-)
Up at the top of your VBA module, above all of your code and variable declarations, you can type Option Base 1 to force all of your arrays to start at index 1 instead of 0
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"}]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.