vba 循环遍历vba excel中的多维数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26352052/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 04:49:47  来源:igfitidea点击:

loop through a multidimensional array in vba excel

excelvba

提问by user147178

I'm trying to loop through a 2d array. The 1d will always be 25, the 2d will have different amounts. Quite often the members of the 1st dimensional will be empty which is the point of the isarray(sent) code. I'm getting a subscript out of range at the part which says for j = 1 to ubound(sent,2)

我正在尝试遍历二维数组。1d 将始终为 25,2d 将具有不同的数量。通常,第一维的成员将是空的,这是 isarray(sent) 代码的重点。我在表示 j = 1 到 ubound(sent,2) 的部分得到一个超出范围的下标

For i = 1 To 25
    If IsArray(sent(i)) Then
        For j = 1 To UBound(sent, 2)
            If concat_multi = "" Then
            concat_multi = sent(i, j)
            Else
            concat_multi = concat_multi & " & " & sent(i, j)
            End If
        Next
        ActiveCell.Offset(1) = concat_multi
        concat_multi = ""
    End If
Next

Here is a screenshot

这是一个屏幕截图

enter image description here

在此处输入图片说明

回答by David Zemens

Look at your object browser. You need to refer to it as Sent(i)is a 1d array. So you have a 1d array wherein each element is another 1d array.

看看你的对象浏览器。您需要将它作为Sent(i)一维数组来引用。所以你有一个一维数组,其中每个元素都是另一个一维数组。

rather than sent(i, j)do sent(i)(j)and initiate the loop thusly:

而不是sent(i, j)这样做sent(i)(j)并启动循环:

for j = 1 To ubound(sent(i))

Technically you should probably be doing this in case you get arrays with base other than 1 (base 0 is common and default unless it is a range array).

从技术上讲,您可能应该这样做,以防您获得基数不是 1 的数组(基数 0 是常见且默认的,除非它是范围数组)。

For j = lbound(sent (i)) to ubound(sent(i))