在VB6中,如果向未定义维数的数组传递到Ubound函数会导致错误,因此在尝试检查其上限之前,我希望检查它是否已被定义维度。如何实现这一点?
这两种方法都可以有效地检测未初始化的数组,但必须包括括号:
(Not myArray) = -1
(Not Not myArray) = 0
我在网上看到了很多关于如何判断数组是否已初始化的建议。下面是一个函数,它将接受任何数组,检查该数组的ubound是什么,重新调整数组为ubound +1(带或不带PRESERVER),然后返回数组的当前ubound而不出现错误。
Function ifuncRedimUbound(ByRef byrefArr, Optional bPreserve As Boolean)
On Error GoTo err:
1: Dim upp%: upp% = (UBound(byrefArr) + 1)
errContinue:
If bPreserve Then
ReDim Preserve byrefArr(upp%)
Else
ReDim byrefArr(upp%)
End If
ifuncRedimUbound = upp%
Exit Function
err:
If err.Number = 0 Then Resume Next
If err.Number = 9 Then ' subscript out of range (array has not been initialized yet)
If Erl = 1 Then
upp% = 0
GoTo errContinue:
End If
Else
ErrHandler.ReportError "modArray", ifuncRedimUbound, "1", err.Number, err.Description
End If
End Function
Dim someArray() as Integer
If someArray Is Nothing Then
Debug.print "this array is not initialised"
End If