Excel VBA函数用于汇总多行单元格

时间:2016-06-02 17:47:57

标签: excel vba excel-vba

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

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

代码:

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

1 个答案:

答案 0 :(得分:1)

以下似乎对我有用:

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