简体   繁体   中英

VBA - Split and IsError Function

I'm struggling with VBA code. I'm working on a ID code generator program. One of the processes involves Split Company Names by words, and taking the first two words. Split has proved to be useful in this tasks, however, when in dealing with Company Names shorter than 2 words I've got a #VALUE! Error.

One way I tried to fix it, was using the ISERROR function, so if I get any error it replaces it with a character, say "X".

In summary, what I'm trying is to capture only the second Word of the Name, if there is no second Word, just display "X".

Public Function idcode_2(text As String) As String
Dim Arr_text As Variant
Dim rz_x, rz2, code As String
Dim i As Integer
Dim c
Arr_text = Split(text, " ", 3)
rz2 = Arr_text(1)
If IsError(rz2) = True Then
    rz2 = "X"
   Else
    rz2 = rz2 & ""
End If
    idcode_2 = rz2
End Function

I'm using VBA in Excel - Microsoft Office Professional Plus 2013.

Arr_text will be a zero-based array - UBound(Arr_text) will give you the upper bound of that array (zero if one item, one if two items, etc)

Public Function idcode_2(text As String) As String

    Dim Arr_text As Variant, rz2

    Arr_text = Split(text, " ", 3)

    If UBound(Arr_text ) > 0 Then
        rz2 = Arr_text(1)
    Else
        rz2 = "x"
    End If

    idcode_2 = rz2

End Function
Public Function idcode_2(text As String) As String
    If Instr(text, " ") > 0 Then
        idcode = Split(text)(1)
    Else
        idcode = "x"
    End If
End Function

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM