Iterate over a possibly empty array in VBA (Excel)

URL dieses Beitrags: http://blog.stefan-macke.com/2012/02/15/iterate-over-a-possibly-empty-array-in-vba-excel/

When you try to iterate over an empty array in VBA like this, you will get a runtime error (index out of bounds):

  1. Sub ArrayTest()
  2.  
  3. Dim testarray() As Integer
  4. Dim i As Integer
  5.  
  6. For i = LBound(testarray) To UBound(testarray) ‘ <– error
  7.    Debug.Print testarray(i)
  8. Next i
  9.  
  10. End Sub

Even if you check the return value of LBounds like this, it results in the same error:

  1. Sub ArrayTest()
  2.  
  3. Dim testarray() As Integer
  4. Dim i As Integer
  5.  
  6. If LBound(testarray) > 1 Then  ‘ <– error
  7.    For i = LBound(testarray) To UBound(testarray)
  8.         Debug.Print testarray(i)
  9.     Next i
  10. End If
  11.  
  12. End Sub

However, to get rid of the error and to iterate over a possibly empty array, the following code works:

  1. Sub ArrayTest()
  2.  
  3. Dim testarray() As Integer
  4. Dim i As Integer
  5.  
  6. On Error Resume Next
  7. If LBound(testarray) > 1 Then
  8.     If Err.Number = 0 Then
  9.         For i = LBound(testarray) To UBound(testarray)
  10.             Debug.Print testarray(i)
  11.         Next i
  12.     End If
  13. End If
  14.  
  15. End Sub

Visual Basic magic ;-)

Einen Kommentar schreiben

XHTML: Diese Tags sind erlaubt: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>