regex - 如何使用正则表达式提取具有特定单位的值并求和

标签 regex excel vba

如何使用正则表达式提取具有特定单位的值并求和。

在A1输入,在A2输出

我只想用 mm 添加值
I only want to add the value with mm

我尝试了 stackoverflow 提供的代码,并在 (\d+(?:\.\d+)?) 之后添加了“?mm”,但出现错误消息。

Function sumNums(str As String) As Double
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 = "(\d+(?:\.\d+)?)?mm"
    If .test(str) Then
        Set cmat = .Execute(str)
        For n = 0 To cmat.Count - 1
            sumNums = sumNums + CDbl(cmat.Item(n))
        Next n
    End If
End With
End Function

最佳答案

正则表达式正在解析的字符串就是这样;字符串。原始的 UDF 使用 CDbl 将这些转换为真实数字,并且它是成功的,因为它们只是数字。要转换带有尾随后缀的字符串数字,请使用 Val。

尝试这个简单的基于正则表达式的 UDF。

Option Explicit


Function sumMMnums(str As String) As Double
    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 = "(\-?\d*\.?\d+)mm"
        If .test(str) Then
            Set cmat = .Execute(str)
            For n = 0 To cmat.Count - 1
                sumMMnums = sumMMnums + Val(cmat.Item(n))
            Next n
        End If
    End With
End Function

enter image description here

关于regex - 如何使用正则表达式提取具有特定单位的值并求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52922426/

相关文章:

excel - 位于许多同名列中的每行值的求和函数

vba - 创建从 Excel 流程图到 MS Word 标题的超链接

excel - Powerpoint VBA 删除空列?

regex - 在groovy中使用正则表达式

regex - 从 Unix 中的一行中提取字符串

python - 处理 diff 文件中的修改

regex - Linux sed - 需要帮助来弄清楚为什么模式匹配不起作用

一个单元格中的 Excel 计算导致另一个单元格

excel - 宏将单元格复制四行而不使用选择

excel - 如何从 Excel 用户窗体中删除 close(x) 选项?