Output array to MsgBox

user3208164 Source

I do PowerShell not VBScript, so I am a little lost. I am trying to list all mapped drives (drive letter and share path) in a MsgBox. I get a type mismatch error when running the script. If I change "Dim myArray()" to "Dim myArray" I get only one item from the variable.

Set objNetwork = WScript.CreateObject("WScript.Network")
Set colDrives = objNetwork.EnumNetworkDrives
Dim myArray()
For i = 0 to colDrives.Count-1 Step 2
 myArray = colDrives.Item(i) & vbTab & colDrives.Item (i + 1)
Next
MsgBox(myArray)

How can I get the data saved to an array, then output to a MsgBox?

vbscript

Answers

answered 4 years ago Bond #1

You can use a string and keep appending (&) to it.

Dim s
For i = 0 To colDrives.Count-1 Step 2
    s = s & colDrives.Item(i) & vbTab & colDrives.Item (i + 1) & vbCrLf
Next

MsgBox s

answered 4 years ago Ansgar Wiechers #2

The reason why your code doesn't work is because you're creating fixed-size array without an actual size (Dim myArray()), and then try to assign values to that array. In VBScript you must assign values to array positions (myArray(pos) = val), and you cannot append to the built-in arrays (at least not without some additional work).

The most straightforward approach in your case would be the method @Bond suggested. However, you can do this with arrays if you want. You just need a resizable array like this:

ReDim myArray(-1)  'empty array
For i = 0 to colDrives.Count-1 Step 2
  ReDim Preserve myArray(UBound(myArray)+1)
  myArray(UBound(myArray)) = colDrives.Item(i) & vbTab & colDrives.Item(i+1)
Next

MsgBox Join(myArray, vbNewLine)

or (using an ArrayList), like this:

Set myArray = CreateObject("System.Collections.ArrayList")
For i = 0 to colDrives.Count-1 Step 2
  myArray.Add colDrives.Item(i) & vbTab & colDrives.Item(i+1)
Next

MsgBox Join(myArray.ToArray, vbNewLine)

Since the size of the array can already be determined before entering the loop you could also dimension the array with the proper size right away to avoid repeated redimensioning (which tends to perform poorly for VBScript built-in arrays):

ReDim myArray(colDrives.Count \ 2 - 1)
For i = 0 to colDrives.Count-1 Step 2
  myArray(i\2) = colDrives.Item(i) & vbTab & colDrives.Item(i+1)
Next

MsgBox Join(myArray, vbNewLine)

Another option would be using a Dictionary:

Set myArray = CreateObject("Scripting.Dictionary")
For i = 0 to colDrives.Count-1 Step 2
  myArray(colDrives.Item(i)) = colDrives.Item(i) & vbTab & colDrives.Item(i+1)
Next

MsgBox Join(myArray.Items, vbNewLine)

comments powered by Disqus