Home » excel » excel – Ubound in multidimension array with differing lengths?

excel – Ubound in multidimension array with differing lengths?

Posted by: admin April 23, 2020 Leave a comment

Questions:

So I have a multidimensional array in Excels VBA. I’m reading a txt file in excel with multiple semicolon delimted lines. each line is read, and split into an array, and added to the multi-D array. Codez:

Dim filenum As Integer        'number of next "free file"
Dim splitCols As Variant
Dim counter As Long
Dim brCodes() As Variant
Dim textline As String
Dim lines As Variant
Dim numrows As Long
Dim numcols As Long

numcols = getNumColumns(ActiveSheet.Name)
numrows = getNumRows(ActiveSheet.Name)

counter = 0

filenum = FreeFile()           'find next free filenum

Open FileName For Input As #filenum    'open file for reading    

'codes are put into an array
While Not EOF(filenum)   'process while file has more lines.

    counter = counter + 1

    Line Input #filenum, textline 'grab current line into textline

    splitCols = Split(textline, ";")

    ReDim Preserve brCodes(1 To counter)

    brCodes(counter) = splitCols

Wend



Close #filenum  'close file\

now what I’d like is to loop through each array in brCodes. I normally use a forloop like –

for i = lbound(brCodes,2) to ubound(brCodes,2)
    'process stuff
 next

but the arrays in brCodes are different lengths. The lines in the text file have differing number of semi colons. it looks like this:

str1;str2;str3;str4;sdtr5
str1;str2;str3;str4;sdtr5;str6;str7
str1;str2;str3;str4

so will I have to add an intermediate step to pull out each array into a temp variable and deal with it like that? or does anyone have a way of getting the ubound of a particular “Row” without pulling it out first?

added

I also tried:

For i = LBound(brCodes, 2) To UBound(brCodes, 2)
    For j = LBound(brCodes(i)) To UBound(brCodes(i))
        MsgBox ("")
    Next
Next

but I get the same subscript out of range error

How to&Answers:

UNTESTED

It’s not a multi-dimensional array. It’s a one-dimensional array of Variants, and each variant holds an array of whatever length. I think your second attempt is close, but it should be like:

For i = LBound(brCodes) To UBound(brCodes)
    For j = LBound(brCodes(i)) To UBound(brCodes(i))
        MsgBox ("")
    Next
Next