Excel VBA函数对多行单元格中的所有数字求和
它是一个可以包含多个换行符的单元格,数字可能有小数 这是我一直在尝试的,但它只是连接数字,我尝试使用CDbl而不是VAL,只是在单元格上给出了一个值错误 代码:Excel VBA函数对多行单元格中的所有数字求和,vba,excel,Vba,Excel,它是一个可以包含多个换行符的单元格,数字可能有小数 这是我一直在尝试的,但它只是连接数字,我尝试使用CDbl而不是VAL,只是在单元格上给出了一个值错误 代码: 以下几点似乎对我有用: 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) va
以下几点似乎对我有用:
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
尝试使用
Chr(10)
而不是vbNewLine
。这不是问题所在,vbNewLine是换行符的正确常量,它可以正确拆分,只是不添加它在Mac上不起作用,而且它不能使用与上述注释和中提到的
不同的十进制分隔符:如果希望它在Mac上工作,则应使用vbNewLine
。关于您对Val
的担忧,我必须同意。这是相当有限的,为了更好的结果,你可能会考虑写你的。我确实做了一个工作,用“,”s代替“”,但不能在MAC中使用不是一个问题。
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