在excel中,如何取出一个单元格内字符串中数字的和。例
 在C1单元格中有一串字符串,“301日霜1晚霜25护手霜3天”
如何使用VBA实现对上述字符串中数字求和。求和结果应该是330

解决方案 »

  1.   

    在excel中添加一个模块,选择“工具-引用”,引用Microsoft VBScript Regular Expressions 5.5 ,添加如下代码到模块中:
    Public Function GetSum(ByVal s As String) As Long
        
        Dim re As RegExp
        Dim mh As Match
        Dim mhs As MatchCollection
        
        Set re = New RegExp
        re.Global = True
        re.Pattern = "\d+"
        If re.Test(s) = True Then
            Set mhs = re.Execute(s)
            For Each mh In mhs
                GetSum = GetSum + mh.Value
            Next
        End IfEnd Function单元格中公式:
    =getsum(A1)
      

  2.   

    如果不想用正则:Public Function GetNumSum(ByVal s As String) As Long
        
        Dim tmp As String
        Dim i As Long
        For i = 1 To Len(s)
            tmp = Mid(s, i, 1)
            If IsNumeric(tmp) Then
                tmp = Val(Mid(s, i))
                GetNumSum = GetNumSum + Val(tmp)
                i = i + Len(tmp) + 1
            End If
        NextEnd Function
      

  3.   

    谢谢您的提示,你的第二个方法很好,就是i = i + Len(tmp) + 1这句,最后加的这个1是多余的。经我测试后,已收到很好的效果。谢了!