Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBScript create a multi-dimensional array and add to it?

This is a doozy for me haha, I've pretty much checked nearly every page on Google Search and I still don't quiet understand how to do it.

I want to create a multi dimensional array in VB Script called data2. Trying the examples that I've seen but I'm getting a "Subscript out of range" error

Dim data2()

sub grabdata
    SQL_query = "SELECT * FROM MSAccess_table"
    Set rsData = conn.Execute(SQL_query)
    Do Until rsData.EOF = True
        ReDim Preserve data2(UBound(data2) + 1)
        data2(UBound(data2)) = Array(rsData("id"),rsData("column_1"),rsData("column_2"),rsData("column_3"),rsData("column_4"))
    rsData.moveNext 
    Loop
end sub

Basically I'm trying to learn how to make a multi-dimensional array in VB script and add to it with a loop. What are some basic examples that can work in my case?

like image 800
Quaking-Mess Avatar asked Mar 22 '23 17:03

Quaking-Mess


1 Answers

(1) The best way to get an ADO resultset into a two-dimensional array is to use the .GetRows method. Then your problem just vanishes.

(2) There are two kind of arrays in VBScript. Fixed arrays are declared by specifying their UBounds:

Dim aFix(2, 3)

They can't be resized. Dynamic arrays can be changed by ReDim [Preserve]. The best way to create such an array is

ReDim aDyn(2, 3)

if you know the starting size, or

Dim aDyn : aDyn = Array()

if you want to start with an empty one. The catch 22 is: you can use Preserve only for the last dimension.

(3) Your

Dim data2()

is an abomination - a fixed array of no size. It's a pity that the 'compiler' is too stupid to catch such a beast that VBScript can't handle properly:

>> Dim data2()
>> WScript.Echo UBound(data2)
>>
Error Number:       9
Error Description:  Subscript out of range

The nastiness of the Dim a() statement is hidden by the fact that a later ReDim will store a proper dynamic array into that variable:

>> Dim data2() ' <-- abomination
>> ReDim data2(1,1) ' <-- overwritten by a dynamic array
>> data2(0,0) = 0
>> ReDim Preserve data2(1,5) ' last dimension increased; 'old' data preserved
>> data2(1,5) = 1
>> WScript.Echo data2(0,0), data2(1,5)
>>
0 1

Update wrt jmbpiano's comment:

(1) I gave evidence that you can't get the UBound for a variable dimmed with (), so I stick to my claim that such beasts are abominations. Just look at the question (or this one) to see that using the () will give you trouble.

(2) I said that you should use ReDim a(KnownUbound) to 'declare' a dynamic array with known size, but I didn't give evidence for the 'Option Explicit'-compatibility of this idiom. So :

Option Explicit
ReDim a(4711)
ReDim b(4,7,1,1)
a(0) = "qed"
b(0,0,0,0) = "qed"
WScript.Echo b(0,0,0,0)

output:

cscript 19888987.vbs
qed
like image 152
Ekkehard.Horner Avatar answered Apr 01 '23 06:04

Ekkehard.Horner