Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Subscript out of range" error when calling LBound() or UBound() on a VBA array

Tags:

vba

ms-access

The following code produces the error "Subscript out of range" and I do not know why. Can someone please explain?

    Dim errorc As Integer
    Dim myarray() As Variant


    errorc = 1

    If Len(Me.txt_Listnum) = 0 Then
    ReDim Preserve myarray(errorc)
    myarray(errorc) = "Numer Listy"
    errorc = errorc + 1
    End If

    If Len(Me.cbo_ByWho) = 0 Then
    ReDim Preserve myarray(errorc)
    myarray(errorc) = "Wystawione przez"
    errorc = errorc + 1
    End If

    If Len(Me.cbo_ForWho) = 0 Then
    ReDim Preserve myarray(errorc)
    myarray(errorc) = "Wystawione na"
    errorc = errorc + 1
    End If

    For i = LBound(myarray) To UBound(myarray)
        msg = msg & myarray(i) & vbNewLine
    Next i

    If errorc > 0 Then
       MsgBox "da" & msg

    End If
like image 910
user3002600 Avatar asked Feb 07 '14 14:02

user3002600


People also ask

How do I fix subscript out of range error in VBA?

If we run this code using the F5 key or manually, we will get Run time error '9': “Subscript out of Range.” To fix this issue, we need to assign the length of an array by using the “ReDim” word. This code does not give any errors.

What is UBound and LBound in VBA?

The LBound function is used with the UBound function to determine the size of an array. Use the UBound function to find the upper limit of an array dimension.

What does UBound do in VBA?

The UBound function is used with the LBound function to determine the size of an array. Use the LBound function to find the lower limit of an array dimension.


1 Answers

Your code will fail if all of the form controls are populated and therefore myarray never gets ReDim'd. For an unititialized dynamic array,

Dim myarray() As Variant

(i.e., one that has not been subsequently sized with ReDim), calling LBound() or UBound() on it will fail with "Subscript out of range."

like image 154
Gord Thompson Avatar answered Nov 14 '22 22:11

Gord Thompson