Excel VBA函数将多行单元格中的所有数字相加

它的一个单元格可以包含多个换行符,而数字可能有小数点

这是我一直在尝试,但它只是连接数字,我试着用CDbl而不是VAL,只是给单元格上的值错误

码:

Public Function somaLinhas(str As String) Dim retorno As Double retorno = 0 Debug.Print ("Trying to sum : " & str) For Each lineStr In Split(str, vbNewLine) Debug.Print ("line to be added : " & lineStr) retorno = retorno + Val(lineStr) Debug.Print (retorno) Next lineStr If retorno > 0 Then somaLinhas = retorno Else somaLinhas = "" End If End Function 

以下似乎为我工作:

 Public Function somaLinhas(str As String) Dim retorno As Double Dim var As Variant Dim i As Long retorno = 0 Debug.Print ("Trying to sum : " & str) var = Split(str, Chr(10)) For i = LBound(var) To UBound(var) Debug.Print ("line to be added : " & lineStr) retorno = retorno + Val(var(i)) Debug.Print retorno Next i If retorno > 0 Then somaLinhas = retorno Else somaLinhas = "" End If End Function