Excel中提取(查找)单元格中的百分数--使用正则表达式形式

    xiaoxiao2024-12-08  73

    日前在一个应用开发中需要提取Excel表格中的百分数,尝试了各种方法不得所愿,最后使用正则表达式解决了,具体代码参考下面:

    '自定义函数:根据传递过来的匹配表达式partn,对strng进行查找,并输出查找的结果 Function RegExpTest(patrn, strng) As String Dim Match, Matches ' 建立变量。 Dim regEx As Object '定义正则表达式对象 Set regEx = CreateObject("vbscript.regexp") regEx.Pattern = patrn ' 设置模式。 regEx.IgnoreCase = True ' 设置是否区分字符大小写。 regEx.Global = True ' 设置全局可用性。 Set Matches = regEx.Execute(strng) ' 执行搜索。 For Each Match In Matches ' 遍历匹配集合。 RetStr = RetStr & "Match found at position " RetStr = RetStr & Match.FirstIndex & ". Match Value is '" RetStr = RetStr & Match.Value & "'." & vbCrLf Next RegExpTest = RetStr End Function Sub RegTest() MsgBox (RegExpTest("\d+(\.\d+)?%", "同比提高了23.8%,环比提高了12%,增长喜人!")) End Sub

    程序的运行效果如下: 上述代码中:[\d.]+% 或 \d+(.\d+)?% 都是可以查找百分数的表达式

    最新回复(0)