多维数组中的Ubound在长度不同的情况下如何使用?

3

我在Excel的VBA中有一个多维数组。我正在使用Excel读取一个包含多个分号分隔行的txt文件。每一行都会被读取,然后被分割成一个数组,并添加到多维数组中。代码如下:

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\

现在我想循环遍历 brCodes 中的每个数组。我通常使用像这样的 for 循环 -

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

但是brCodes中的数组长度不同。文本文件中的行具有不同数量的分号。它看起来像这样:

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

那么我需要添加一个中间步骤来将每个数组提取到临时变量中并进行处理吗?或者是否有一种方法可以在不先提取它的情况下获取特定“行”的ubound?

添加

我也尝试过:

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

但我收到了相同的下标越界错误。

1个回答

3

未经测试

它不是一个多维数组。它是一个由Variants组成的一维数组,每个变体都持有一个任意长度的数组。我认为你的第二次尝试很接近,但应该像这样:

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

谢谢!我甚至没有想到这会起作用,只是因为在砸头之前还有一件事情要尝试...我一直在尝试使用实际的二维数组来完成这些操作,我想上次我做这个时使用的是真正的二维数组,所以我无法弄清楚为什么那些方法都不起作用,而且我把它搞得太复杂了。 - user1759942
很高兴能帮忙。好问题。这是一个令人困惑的情况! - Doug Glancy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接