user1341676
user1341676

Reputation:

ArrayList with Arrays

It seems that more "complex" ArrayLists are not widely used, since I'm unable to find any concrete, helpful info about it.

I'm trying to create an ArrayList of Arrays (and eventually an ArrayList of ArrayLists of Arrays), but I seem unable to either add Arrays to the ArrayList, or access the Array's elements. All this is done using VBScript in QTP.

(The code reads from an Excel file, which is working fine.)

Set my_sheet = ExcelObject.sheets.item(testCaseSheet)
testCase     = CreateObject("System.Collections.ArrayList")

Function getTestsCaseActions (row, col)
    Do While my_sheet.cells(row, 2).Value <> ""
        MsgBox tempArray(0) & " -> " & tempArray(1) 'WORKS FINE - THE VALUES ARE PRINTED
        testCase.Add tempArray

        row = row+2
    Loop
    End Function

getTestsCaseActions 3, 4

'This is not working - how do I access the arrays and their values in the arraylist?
For Each ArrayItem in testCase
    MsgBox ArrayItem(0)' & ", " & ArrayItem(1)
    'MsgBox "Hey!"
Next

Now, I realize that For Each ArrayItem in testCase is probably wrong, but I cannot find out what to use? The elements added to the ArrayList are, after all, Arrays. If I uncomment the line MsgBox "Hey!", it's written once, even though the ArrayList should have 3 Arrays.

Upvotes: 2

Views: 18810

Answers (1)

Ekkehard.Horner
Ekkehard.Horner

Reputation: 38745

Short answer: The correct way to use an ArrayList Of Arrays if you just need read access (after a successful initialization):

Option Explicit

Dim alA : Set alA = CreateObject("System.Collections.Arraylist")
alA.add Split("A B C")
alA.add Split("D E F")
alA.add Split("I J K")
WScript.Echo "---- For Each In"
Dim aX
For Each aX In alA
    WScript.Echo TypeName(aX), Join(aX)
Next
WScript.Echo "---- For To"
Dim i
For i = 0 To alA.Count - 1
    WScript.Echo TypeName(alA(i)), Join(alA(i))
Next

output:

cscript 19915175.vbs
---- For Each In
Variant() A B C
Variant() D E F
Variant() I J K
---- For To
Variant() A B C
Variant() D E F
Variant() I J K

ReDim Preserve answer(UBound(answer) + 1):

No problems with an ArrayList Of ArrayLists of Arrays (as long we are talking about read access and you don't mess it up):

Dim alB : Set alB = CreateObject("System.Collections.Arraylist")
alB.Add alA
WScript.Echo "alB(0)(0)(0) =>", alB(0)(0)(0)
WScript.Echo "alB(0)(2)(2) =>", alB(0)(2)(2)

output:

alB(0)(0)(0) => A
alB(0)(2)(2) => K

Upvotes: 1

Related Questions