teddy2
teddy2

Reputation: 390

how to check if Split()result is valid?

I have a function LastItem which returns the last word from the string. It works fine for strings with value but for blanks like "" it fails.

I am checking if Split returned an Array. Even for blank string the IsArray() returns true. Is there a way to Fix it.

Errors are mentioned as comment in the code.

Sub test()

Debug.Print LastItem("a b c")
Debug.Print LastItem("a")
Debug.Print LastItem("") '''' ===> Error for this one

End Sub

Public Function LastItem(source As String) As String

    Dim arr
    arr = Split(source, Space(1))

    If IsArray(arr) Then
        LastItem = arr(UBound(arr)) '''' ===> For LastItem("") error is [Subscript out of range]
    Else
        LastItem = source
    End If

End Function  

Upvotes: 1

Views: 658

Answers (2)

BigBen
BigBen

Reputation: 50008

Split always returns an array so an IsArray check is unnecessary.

How about this? Bail early if the input is a zero-length string.

Public Function LastItem(source As String) As String
    If source = vbNullString Then Exit Function

    Dim arr
    arr = Split(source, Space(1))

    LastItem = arr(UBound(arr))
End Function

Upvotes: 2

cyboashu
cyboashu

Reputation: 10433

Check if upper bound is greater than -1


Public Function LastItem(source As String) As String

    Dim arr
    arr = Split(source, Space(1))

    '/ Check if upper bound is greater than -1
    If UBound(arr) > -1 Then
        LastItem = arr(UBound(arr))
    Else
        LastItem = source
    End If

End Function

Upvotes: 3

Related Questions