AddyProg
AddyProg

Reputation: 3050

Getting Numerics from end of a String in VBA

How can I get numeric from end of a string For example if string is 24Text147 i should get 147 only or if string is text12 i should get 12 only. Here is what I have found but it gives all the numerics in a string

Function onlyDigits(s As String) As String

    Dim retval As String    
    Dim i As Integer        

    retval = ""
                                     '
    For i = 1 To Len(s)
        If mId(s, i, 1) >= "0" And mId(s, i, 1) <= "9" Then
            retval = retval + mId(s, i, 1)
        End If
    Next
                             '
    onlyDigits = retval
End Function

Upvotes: 0

Views: 72

Answers (2)

ZAT
ZAT

Reputation: 1347

Another way:

Function onlyDigits(s As String) As String
For i = Len(s) To 1 Step -1
    If IsNumeric(Right(s, i)) Then
    onlyDigits = Right(s, i)
    Exit Sub
    End If
Next
End Function

Upvotes: 0

Tim Williams
Tim Williams

Reputation: 166126

Function onlyDigits(s As String) As String
    Dim retval As String
    Dim i As Integer

    retval = ""
                                     '
    For i = Len(s) To 1 Step -1
        If Mid(s, i, 1) Like "#" Then
            retval = Mid(s, i, 1) & retval
        Else
            Exit For
        End If
    Next
    onlyDigits = retval
End Function

Upvotes: 1

Related Questions