VBA. How to find position of first digit in string

Viewed 42249

I have string "ololo123". I need get position of first digit - 1. How to set mask of search ?

7 Answers

An improved version of spere's answer (can't edit his answer), which works for any pattern

Private Function GetNumLoc(textValue As String, pattern As String) As Integer
    For GetNumLoc = 1 To (Len(textValue) - Len(pattern) + 1)
        If Mid(textValue, GetNumLoc, Len(pattern)) Like pattern Then Exit Function
    Next

    GetNumLoc = 0
End Function

To get the pattern value you can use this:

Private Function GetTextByPattern(textValue As String, pattern As String) As String
    Dim NumLoc As Integer
    For NumLoc = 1 To (Len(textValue) - Len(pattern) + 1)
        If Mid(textValue, NumLoc, Len(pattern)) Like pattern Then
            GetTextByPattern = Mid(textValue, NumLoc, Len(pattern))
            Exit Function
        End If
    Next    

    GetTextByPattern = ""
End Function

Example use:

dim bill as String
bill = "BILLNUMBER 2202/1132/1 PT2200136"

Debug.Print GetNumLoc(bill , "PT#######")
'Printed result:
'24

Debug.Print GetTextByPattern(bill , "PT#######")
'Printed result:
'PT2200136
Related