有没有办法循环,直到VBA中的多维数组已满?

时间:2017-10-24 15:33:21

标签: vba excel-vba loops multidimensional-array excel

是否有一种简单的方法来实现循环,直到多维数组中的每个值对于类型都不是“空” - 所以循环直到字符串数组填充非空字符串的值等等。

我想要的伪代码示例:

 Dim MultiArray(100,100) As String

 Do Until MultiArray(0,0) To MultiArray (100,100) Is Not = ""
      'Operations
 Loop

2 个答案:

答案 0 :(得分:2)

这“简单”吗?

For i = 0 To 100

    For j = 0 To 100

        'Operations
        MultiArray(i, j) = 1

    Next j

Next i

修改

Function IsArrayFilled(ByRef Multi_Array() As String) As Boolean

    Dim i As Long, j As Long

    For i = LBound(Multi_Array, 1) To UBound(Multi_Array, 1)

        For j = LBound(Multi_Array, 2) To UBound(Multi_Array, 2)

            If Multi_Array(i, j) = "" Then ' If there are ANY blank strings, then terminate the function immediately and return false

                IsArrayFilled = False
                Exit Function

            End If

        Next j

    Next i

    ' If we got through the whole array without finding any blank strings, then return true
    IsArrayFilled = True

End Function

Sub Test()

    Dim MultiArray(0 To 100, 0 To 100) As String

    Do While Not IsArrayFilled(MultiArray)

        'Operations

    Loop

End Sub

请注意,这是一个非常昂贵的函数,因为它会在每次检查时尝试遍历整个数组,即在数组填充时逐渐变慢。我不确定为什么你需要检查空字符串以及为什么你不能简单地遍历数组一次。但是,这是我知道做你要求的唯一方法。

答案 1 :(得分:1)

你有一个二维数组,所以唯一可能迭代所有值的循环结构是{​​{3}}。

如果我正确理解了您的问题陈述,您希望在遇到空字符串值时突破该嵌套循环。

该阵列中的实际内容做了很多假设。让我们分别在维度索引1和2中假设行/列布局,并且因为我们不知道数据来自何处(工作表范围?某个文件?硬编码?),让我们不要硬编码循环的下限和上限:

Dim row As Long
For row = LBound(data, 1) To UBound(data, 1)

    Dim break As Boolean
    Dim col As Long
    For col = LBound(data, 2) To UBound(data, 2)

        'Operations

        Dim value As Variant
        value = CStr(data(row, col))

        If value = vbNullString Then
            break = True
            Exit For
        End If

    Next
    If break Then Exit For
Next

虽然存在一个问题:只要遇到空字符串,这就会突破循环 - 这可能是您想要的,也可能不是。

如果你想在找到每一列包含空字符串的行时停止迭代行,那么这就不是了。你需要更精确的逻辑。像这样:

Dim row As Long
For row = LBound(data, 1) To UBound(data, 1)

    Dim rowContents As String
    Dim col As Long
    For col = LBound(data, 2) To UBound(data, 2)

        'Operations

        rowContents = rowContents & CStr(data(row, col))

    Next
    If Strings.Trim(rowContents) = vbNullString Then Exit For
Next

请注意,如果有任何"单元格,这两个循环都会爆炸。包含错误值。您可以使用IsError函数来防范它。

但话说回来,假设您正在迭代。如果你在Excel中并且你正在迭代第二个维度代表行的二维数组,那么一旦你找到了一个"行,你就会想要停止一个循环。 #34;只包含空"单元格",然后您尝试解决的真实问题是"找到范围内的最后一行#34;并且你没有做任何事情,nested For loop是你真正想要使用的:

With Sheets("Sheet1")
    If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
        lastrow = .Cells.Find(What:="*", _
                      After:=.Range("A1"), _
                      Lookat:=xlPart, _
                      LookIn:=xlFormulas, _
                      SearchOrder:=xlByRows, _
                      SearchDirection:=xlPrevious, _
                      MatchCase:=False).Row
    Else
        lastrow = 1
    End If
End With

我可以继续推断你一整天都想要实现的目标,但我会在这里停下来。