Populating VBA dynamic arrays

前端 未结 5 1107
悲哀的现实
悲哀的现实 2020-12-07 13:19

The following code gives me error 9 \"subscript out of range\". I meant to declare a dynamic array so that the dimension changes as I add elements to it. Do I have to create

5条回答
  •  無奈伤痛
    2020-12-07 13:50

    I see many (all) posts above relying on LBound/UBound calls upon yet potentially uninitialized VBA dynamic array, what causes application's inevitable death ...

    Erratic code:

    Dim x As Long Dim arr1() As SomeType ... x = UBound(arr1) 'crashes

    Correct code:

    Dim x As Long Dim arr1() As SomeType ... ReDim Preserve arr1(0 To 0) ... x = UBound(arr1)

    ... i.e. any code where Dim arr1() is followed immediatelly by LBound(arr1)/UBound(arr1) calls without ReDim arr1(...) in between, crashes. The roundabout is to employ an On Error Resume Next and check the Err.Number right after the LBound(arr1)/UBound(arr1) call - it should be 0 if the array is initialized, otherwise non-zero. As there is some VBA built-in misbehavior, the further check of array's limits is needed. Detailed explanation may everybody read at Chip Pearson's website (which should be celebrated as a Mankind Treasure Of VBA Wisdom ...)

    Heh, that's my first post, believe it is legible.

提交回复
热议问题