Dynamic arrays in VBScript with Split(). Is there a better way?

12,549

Solution 1

The solution I usually go for is to resize the array each time I add new item to it. In that way the end array will never have any unused entries.

ReDim aArray(-1)

For i = 1 To 10
    ReDim Preserve aArray(UBound(aArray) + 1)
    aArray(UBound(aArray)) = i
Next

MsgBox Join(aArray, "," & vbNewLine)

Other solution proposed by Carlos is to do it using Dictionary object which is probably cleaner solution:

Set dic = CreateObject("Scripting.Dictionary")

dic.Add "Item1", ""
dic.Add "Item2", ""
dic.Add "Item3", ""

msgbox Join(dic.Keys, "," & vbNewLine)

Thanks, Maciej

Solution 2

How about a Dictionary object?

Share:
12,549
Carlos Nunez
Author by

Carlos Nunez

I love coding things, helping people, riding bikes and having fun. Let's connect on Linkedin

Updated on June 05, 2022

Comments

  • Carlos Nunez
    Carlos Nunez almost 2 years

    A lot of the scripts I write at my job depend on the creation of dynamically-sizable arrays. Arrays in VBScript make this a pretty arduous task, as one has to Redim arrays every time one wants to resize them. To work around this, I've started making comma-delimited strings and using Split(...) to create 1D arrays out of it. While this works fantastic for me, I've wondered whether VBScript has a more efficient way of handling this. So I ask StackOverflow; are there?

    Disclaimer: I'm fully aware that VBScript is a pretty substandard scripting language, but Python requires extra software, which is a bit of a hassle for server automation, and PowerShell isn't a core component yet. I'm learning them both, though!