Consider this code in MS Word VBA:
Sub Test()
Dim x() As Document
ReDim Preserve x(UBound(x) + 1)
Set x(UBound(x)) = Application.ActiveDocument
End Sub
If I place the cursor inside and hit F5 to run it, I get an error
subscript out of range
on ReDim Preserve x(UBound(x) + 1)
. Specifically, it doesn't like UBound(x)
, although it should return -1
based on MSDN (see under "return value").
Now, if I set a break point on ReDim Preserve x(UBound(x) + 1)
, run it, and then hover the cursor over UBound(x)
, it indicates the same thing:
But I've discovered that if I then hover over the variable x
in the following line:
and then go back and again hover over UBound(x)
in the line above, I get a different result:
Then, if I hit F5 to run the rest of the code, indeed, I get no error that time.
Furthermore, if I change my code to add IsArray(x)
:
Sub Test()
Dim x() As Document
IsArray (x) 'This is just here to preclude VBA array "bug"
ReDim Preserve x(UBound(x) + 1)
Set x(UBound(x)) = Application.ActiveDocument
End Sub
It also runs fine. What is going on, and how can I get my code to work at runtime without the IsArray(x)
hack?
MSDN:
If Array has only one element, UBound returns 0. If Array has no elements, for example if it is a zero-length string, UBound returns -1.
It isn't that the array has no elements, it is un-initialized, or doesn't have dimensions. You shouldn't rely on the value of UBound
without first using ReDim
on the array at least once, or without the use of error handling.
A better approach is to use error handling:
Dim x() As Document
Dim n As Long
On Error Resume Next
Err.Clear
n = LBound(x)
If Err.Number = 0 Then
Debug.Print "Array is allocated."
Else
Debug.Print "Array is not allocated."
End If
See this link for other considerations.
Alternatively, if possible, ensure that the array is dimensioned ( ReDim
) as least once.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.