加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

用ExcelVBA正则表达式让所有括号中的数字相加

(2014-04-19 08:49:16)
标签:

excel

vba

正则表达式

教育

分类: ExcelVBA

http://s5/mw690/001f8HsBgy6IdJVaWLG54&690
单元格内容:
a(111)
b(6)w(9)
c(4)
m(23)
n(2)d(1)d(1)d(1)

d(1)

想用公式达到 111+6+9+4+23+2+1+1+1+1 =159  这样的效果,A6没有就跳过。
也就是让所有括号中的数字相加。

Public Function 求和(rng As Range)
    Dim m, n, Mat, str, rg As Range
    With CreateObject("Vbscript.Regexp")
        .Global = True    'Global属性:查找范围:True全部查找,False只查找第1个,默认False
        .MultiLine = True    '匹配多行为True
        .IgnoreCase = False    '如果赋值为True不区分大小写,如果赋值为False或者不写,就区分大小写
        .Pattern = "\d+"    'Pattern属性:书写正则表达式,默认为"
        For Each rg In rng
            Set Mat = .Execute(rg)   'Execute方法:返回匹配成功的结果,是一个对象
            For Each m In Mat
                str = str & "+" & m
            Next
        Next
    End With
    求和 = Application.Evaluate(str)
End Function

 

Public Function 求和2(rng As Range)
    Dim m, n, Mat, str, rg As Range
    With CreateObject("Vbscript.Regexp")
        .Global = True    'Global属性:查找范围:True全部查找,False只查找第1个,默认False
        .MultiLine = True    '匹配多行为True
        .IgnoreCase = False    '如果赋值为True不区分大小写,如果赋值为False或者不写,就区分大小写
        .Pattern = "\d+"    'Pattern属性:书写正则表达式,默认为"
        For Each rg In rng
            Set Mat = .Execute(rg)   'Execute方法:返回匹配成功的结果,是一个对象
            For Each m In Mat
                str = str + Val(m)
            Next
        Next
    End With
    求和2 = str
End Function

 

Function SunNum(rng)
    With CreateObject("vbscript.regexp")
        .Pattern = "\(\d+\)"
        .Global = True
        For Each c In rng
            For Each m In .Execute(c)
                s = s & "+" & m
            Next
        Next
    End With
    SunNum = Application.Evaluate(s)
End Function

 

Function SumNum(rng As Range) '兼容括号内带小数点的数字
    Dim rg As Range, n, str As String
    With CreateObject("vbscript.regexp")
        .Pattern = "\(\d+\.{0,1}\d{0,}\)"
        .Global = True
        For Each rg In rng
            For Each m In .Execute(rg)
                str = str & "+" & m
            Next
        Next
    End With
    SumNum = Application.Evaluate(str)
End Function

 

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有