如何从字符串中获取数字并添加它们?

时间:2018-06-05 10:49:28

标签: excel vba

我想从字符串中找到一个数字并返回值。

如果一个字符串包含多个数字,那么它应该在字符串中添加所有数字并返回总数。

对于Ex:“20分钟用于团队会议,90分钟用于培训”因此返回值应为110(90 + 20)

2 个答案:

答案 0 :(得分:4)

尝试

Option Explicit

Function sumNums(str As String) As Long
    Dim n As Long
    Static rgx As Object, cmat As Object

    If rgx Is Nothing Then
        Set rgx = CreateObject("VBScript.RegExp")
    End If

    With rgx
        .Global = True
        .MultiLine = True
        .Pattern = "[0-9]{1,7}"
        If .test(str) Then
            Set cmat = .Execute(str)
            For n = 0 To cmat.Count - 1
                sumNums = sumNums + cmat.Item(n)
            Next n
        End If
    End With
End Function

enter image description here

答案 1 :(得分:0)

尝试一下:

Public Function NumEx(s As String) As Double
    Dim L As Long, i As Long, s2 As String
    Dim CH As String

    L = Len(s)
    NumEx = 0
    If L = 0 Then Exit Function
    s2 = ""

    For i = 1 To L
        CH = Mid(s, i, 1)
        If CH Like "[0-9]" Or CH = "." Then
            s2 = s2 & CH
        Else
            s2 = s2 & " "
        End If
    Next i

    s2 = Application.WorksheetFunction.Trim(s2)
    arry = Split(s2, " ")

    For Each a In arry
        NumEx = NumEx + a
    Next a
End Function

enter image description here

注意:

  • 输入字符串转换为数字数组
  • 然后将数组相加

修改#1:

VBA UDF可以通过两种方式使用:

  1. 在单元格中(见上图)
  2. 来自 Sub 或来自其他UDF
  3. 以下是第二种方式的示例:

    enter image description here