让我们说一个单元格中有一些文字是
“这是一个文本块(.7),在这个文本块(1.2)中有数字(2.5),这些数字需要加在一起(.4)”
所有这些数字之和的答案是.7 + 1.2 + 2.5 + .4 = 4.8
我的问题是,有没有一种方法可以让excel从一个文本块中添加所有数字并输出答案?它总是数字的总和,数字总是正数。数字的数量会有所不同,可能是2,它可能是15,可能是任何东西。
到目前为止我尝试过:我尝试过“= sum”并突出显示整个单元格,它总是给出答案“0”
答案 0 :(得分:2)
尝试以下用户定义函数:
Public Function Addum(rng As Range) As Double
Dim s As String, L As Long, temp As String
Dim CH As String
s = rng.Value
L = Len(s)
For i = 1 To L
CH = Mid(s, i, 1)
If CH Like "[0-9]" Or CH = "." Then
temp = temp & CH
Else
temp = temp & " "
End If
Next i
temp = Application.WorksheetFunction.Trim(temp)
arr = Split(temp, " ")
For Each a In arr
Addum = Addum + CDbl(a)
Next a
End Function
用户定义函数(UDF)非常易于安装和使用:
如果保存工作簿,UDF将随之保存。 如果您在2003年之后使用的是Excel版本,则必须保存 该文件为.xlsm而不是.xlsx
删除UDF:
从Excel使用UDF:
= myfunction的(A1)
要了解有关宏的更多信息,请参阅:
http://www.mvps.org/dmcritchie/excel/getstarted.htm
和
http://msdn.microsoft.com/en-us/library/ee814735(v=office.14).aspx
有关UDF的详细信息,请参阅:
http://www.cpearson.com/excel/WritingFunctionsInVBA.aspx
必须启用宏才能使其生效!
修改#1:强>
原始代码尝试将独立期间转换为数字。用这个版本替换原始UDF:
Public Function Addum(rng As Range) As Double
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'
' VERSION #2
'
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Dim s As String, L As Long, temp As String
Dim CH As String
s = rng.Value
L = Len(s)
For i = 1 To L
CH = Mid(s, i, 1)
If CH Like "[0-9]" Or CH = "." Then
temp = temp & CH
Else
temp = temp & " "
End If
Next i
temp = Application.WorksheetFunction.Trim(temp)
arr = Split(temp, " ")
For Each a In arr
If IsNumeric(a) Then
Addum = Addum + CDbl(a)
End If
Next a
End Function
修改#2:强>
此版本(VERSION 3)只会处理封装在parens中的数字:
Public Function Addum(rng As Range) As Double
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'
' VERSION #3
'
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Dim s As String, L As Long, temp As String
Dim CH As String
s = rng.Value
L = Len(s)
For i = 1 To L
CH = Mid(s, i, 1)
If CH Like "[0-9]" Or CH = "." Or CH = "(" Or CH = ")" Then
temp = temp & CH
Else
temp = temp & " "
End If
Next i
temp = Application.WorksheetFunction.Trim(temp)
arr = Split(temp, " ")
For Each a In arr
If Left(a, 1) = "(" Then
a = Mid(a, 2, Len(a) - 2)
If IsNumeric(a) Then
Addum = Addum + CDbl(a)
End If
End If
Next a
End Function