获取字符串上的最后一个数字块

时间:2016-12-26 11:37:54

标签: excel string vba

假设我有以下列表:

2John n3
Mi33chael 445
321Peter 1234DD
44434Jack       44
Anna333Y

是否可以通过VBA获取每一行的最后一位数字(或数字块)?

我的意思是,我需要输出(在这种情况下):

3
445
123
44
333

1 个答案:

答案 0 :(得分:2)

尝试下面的UDF:

Function GetLastDigits(byMixedString As String) As Variant

    Dim Entries As String
    Dim RegEx As Object, Matches As Object, Match As Object

    Entries = byMixedString
    Set RegEx = CreateObject("vbscript.regexp")

    With RegEx
        .MultiLine = False
        .Global = True
        .IgnoreCase = True
        .Pattern = "(\d+)" ' Match any set of digits
    End With

    Set Matches = RegEx.Execute(Entries)

    If VBA.Left(Matches(Matches.Count - 1), 1) = 0 Then
        GetLastDigits = VBA.Right(Matches(Matches.Count - 1), Len(Matches(Matches.Count - 1)) - 1)
    Else
        GetLastDigits = Matches(Matches.Count - 1)
    End If

End Function

运行此UDF的工作表结果(您需要在公式括号栏中输入混合字符串):

enter image description here