从VBA中的String结尾获取Numerics

时间:2014-11-17 06:20:27

标签: vba excel-vba excel

如何从字符串末尾获取数字 例如,如果字符串是24Text147,我应该只获得147,或者如果字符串是text12,我应该只获得12。 这是我发现的,但它给出了字符串中的所有数字

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

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

另一种方式:

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