VBA:当数组为空时不要进入循环

use*_*776 1 vba

我有一个循环,看起来像这样:

For Each article In artAll
Next
Run Code Online (Sandbox Code Playgroud)

或者像这样:

For i = 0 To Ubound(artAll)
Next
Run Code Online (Sandbox Code Playgroud)

当数组长度为0时,我收到一条错误消息.当数组为空时跳过循环的好方法是什么?我怀疑我应该使用

On Error Goto
Run Code Online (Sandbox Code Playgroud)

但我需要帮助最终确定解决方案.

Dan*_*Dan 11

If Len(Join(artAll, "")) = 0 Then
     'your for loops here
Run Code Online (Sandbox Code Playgroud)

应该管用

  • 这不适用于大型阵列. (8认同)

ass*_*ias 7

我用这个函数来测试空数组:

Public Function isArrayEmpty(parArray As Variant) As Boolean
'Returns false if not an array or dynamic array that has not been initialised (ReDim) or has been erased (Erase)

    If IsArray(parArray) = False Then isArrayEmpty = True
    On Error Resume Next
    If UBound(parArray) < LBound(parArray) Then isArrayEmpty = True: Exit Function Else: isArrayEmpty = False

End Function
Run Code Online (Sandbox Code Playgroud)

然后在你的主要代码中:

If isArrayEmpty(yourArray) Then
   'do something - typically:
   MsgBox "Empty Array"
   Exit Function
End If

For i = LBound(yourArray,1) To UBound(yourArray,1)
   'do something
Next i
Run Code Online (Sandbox Code Playgroud)