我想从字符串中找到一个数字并返回值。
如果一个字符串包含多个数字,那么它应该在字符串中添加所有数字并返回总数。
对于Ex:“20分钟用于团队会议,90分钟用于培训”因此返回值应为110(90 + 20)
答案 0 :(得分:4)
尝试regex。
Option Explicit
Function sumNums(str As String) As Long
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 = "[0-9]{1,7}"
If .test(str) Then
Set cmat = .Execute(str)
For n = 0 To cmat.Count - 1
sumNums = sumNums + cmat.Item(n)
Next n
End If
End With
End Function
答案 1 :(得分:0)
尝试一下:
Public Function NumEx(s As String) As Double
Dim L As Long, i As Long, s2 As String
Dim CH As String
L = Len(s)
NumEx = 0
If L = 0 Then Exit Function
s2 = ""
For i = 1 To L
CH = Mid(s, i, 1)
If CH Like "[0-9]" Or CH = "." Then
s2 = s2 & CH
Else
s2 = s2 & " "
End If
Next i
s2 = Application.WorksheetFunction.Trim(s2)
arry = Split(s2, " ")
For Each a In arry
NumEx = NumEx + a
Next a
End Function
注意:强>
修改#1:强>
VBA UDF可以通过两种方式使用: