Salman Arshad
Salman Arshad

Reputation: 272106

UBound inside Redim Preserve throws "Subscript out of range"

I want to use a dynamic array containing arbitrary number of strings. The array is filled by if ... then logic instead of a loop. I keep getting Subscript out of range error:

Dim Files() As String

If True Then
    ReDim Preserve Files(UBound(Files) + 1) ' Throws "Subscript out of range" error
    Files(UBound(Files)) = "foo.pdf"
End If

If True Then
    ReDim Preserve Files(UBound(Files) + 1)
    Files(UBound(Files)) = "bar.txt"
End If

If True Then
    ReDim Preserve Files(UBound(Files) + 1)
    Files(UBound(Files)) = "baz.jpg"
End If

I have a function declared like this:

Function SendFiles(Files() As String)

I want to get rid of this error without using variants if possible. I can rewrite the code but I cannot use a loop.

Upvotes: 1

Views: 576

Answers (2)

Erik A
Erik A

Reputation: 32642

Your array is not initialized at the start, and you can't Redim Preserve an uninitialzed array.

If you want a string array to hold a variable amount of items, possibly zero, you can start with initializing it to a zero-length array using Split:

Files = Split(vbNullString)

Upvotes: 2

iDevlop
iDevlop

Reputation: 25262

You could also allocate a large enough array and resize to used size afterwards. That way you have only 1 resize. Something like this:

Dim Files(1000) As String, i as long

If True Then
    Files(i) = "foo.pdf": i = i+1
End If

If True Then
    Files(i) = "bar.txt": i = i+1
End If

If True Then
    Files(i) = "baz.jpg": i = i+1
End If

redim preserve Files(i-1)

Upvotes: 1

Related Questions