从字符串中提取数字集,并在新字符串中以逗号分隔值的形式返回

时间:2013-07-12 15:37:05

标签: excel excel-vba excel-formula vba

任何人都可以给我任何关于如何实现这一点的指示吗?我已经设法提取所有数字,但无法将它们分开到正确的位置。希望通过excel功能实现这一目标,但VBA也可以。

这就是我现在所拥有的:

=SUMPRODUCT(MID(0&A1;LARGE(INDEX(ISNUMBER(--MID(A1;ROW($1:$25);1))*ROW($1:$25);0);ROW($1:$25))+1;1)*10^ROW($1:$25)/10)

所需结果的示例:

Cell A1:                     Result:

123abc                       123
abc456                       456
123abc456                    123,456
789sometext753               789,753
6ty cents, 5%                6,5

2 个答案:

答案 0 :(得分:1)

你可以试试这个UDF:

Public Function GetNumbers(sMark As String) As String

    'regexp declaration
    Dim objRegExp As Object
    Set objRegExp = CreateObject("vbscript.regexp")

    With objRegExp
        .Global = True
        .Pattern = "(\d+)\D*"

        Dim i As Long
        If .Execute(sMark).Count > 1 Then
            For i = 0 To .Execute(sMark)(0).submatches.Count
                GetNumbers = GetNumbers & .Execute(sMark)(i).submatches(0) & ","
            Next
        Else
            GetNumbers = .Execute(sMark)(0).submatches(0) & ","
        End If
    End With
    GetNumbers = Left(GetNumbers, Len(GetNumbers) - 1)

End Function

对您提供的示例进行了测试和测试,并希望它能够满足您所需的所有情况。

答案 1 :(得分:0)

您可以使用此UDF:

Function GetNums(target As Range)
    Dim MyStr As String, i As Integer
    MyStr = ""
    If Len(target.Value) = 0 Then GoTo GoExit
    For i = 1 To Len(target.Value)
        If IsNumeric(Mid(target, i, 1)) Then
            MyStr = MyStr & Mid(target, i, 1)
        Else
            MyStr = MyStr & " "
        End If
    Next i
GoExit:
    GetNums = Application.WorksheetFunction.Substitute(Application.WorksheetFunction.Trim(MyStr), " ", ",")
End Function