如果与下标超出范围进行比较

时间:2015-07-15 12:30:00

标签: arrays vba if-statement

我不明白为什么代码bello执行时的值 strArray(0)是下标超出范围。我的booleanVariable变为true,我不希望这样。

If Left(strArray(0), 3) = "Usu" Then
     booleanVariable = True    
End If

1 个答案:

答案 0 :(得分:0)

在尝试进行字符串操作之前,确保数组(0)不为空

sub t
If Initialized(strArray) Then ' is array setup
    If strArray(0) <> "" Then ' if array has value
        If Left(strArray(0), 3) = "Usu" Then
             booleanVariable = True
        End If
    Else
        MsgBox "No value in array"
    End If
Else
    MsgBox "Array not setup"
End If
end sub

Function Initialized(val) As Boolean
On Error GoTo errHandler
    Dim i

    If Not IsArray(val) Then GoTo exitRoutine

    i = UBound(val)

    Initialized = True
exitRoutine:
    Exit Function
errHandler:
    Select Case Err.Number
        Case 9 'Subscript out of range
            GoTo exitRoutine
        Case Else
            Debug.Print Err.Number & ": " & Err.Description, _
                "Error in Initialized()"
    End Select
    Debug.Assert False
    Resume
End Function