|
- Sub 按钮1_Click()
- Call qs
- End Sub
- Function SumNumbersInString(inputString As String) As Double
- Dim regex As Object
- Set regex = CreateObject("VBScript.RegExp")
-
- ' 正则表达式模式,匹配所有数字
- regex.Pattern = "\d+(\.\d+)?" ' 匹配整数和小数
- regex.Global = True ' 匹配所有出现的数字
-
- Dim matches As Object
- Set matches = regex.Execute(inputString)
-
- Dim total As Double
- total = 0
-
- ' 遍历所有匹配的数字并累加
- Dim match As Object
- For Each match In matches
- total = total + CDbl(match.Value)
- Next match
-
- ' 返回总和
- SumNumbersInString = total
-
- ' 清理
- Set regex = Nothing
- Set matches = Nothing
- End Function
- Sub qs()
- Dim testString As String
- With Sheet3
- arr = .Range("k3:k" & .Cells(Rows.Count, "k").End(3).Row)
- For i = 1 To UBound(arr)
- If arr(i, 1) <> Empty Then
- testString = arr(i, 1)
- ' 调用函数并显示结果
- Dim result As Double
- result = SumNumbersInString(testString)
- arr(i, 1) = result
- End If
- Next
- .Range("m3:m10000").ClearContents
- .Range("m3").Resize(UBound(arr), 1) = arr
- End With
- End Sub
复制代码 |
|