我的Word宏中有一个vba函数,它以逗号分隔的数字列表作为字符串返回。例如;
var = (1.5, 2, 3, 5)
我如何添加它们以找到总和?
答案 0 :(得分:2)
将","
替换为"+"
,并在字符串上使用Evaluate
公式。注意:必须创建对Excel实例的引用,至少可以说有点笨重!我找不到相当于Evaluate函数的单词,这似乎有点奇怪:
Option Explicit
Public Sub test()
Dim inputStr As String, oXL As Object
inputStr = "1.5, 2, 3, 5"
With CreateObject("Excel.Application")
MsgBox .Evaluate(Replace(inputStr, ",", "+"))
.Quit
End With
End Sub
答案 1 :(得分:1)
您需要将字符串拆分为字符串数组,使用Val
,CDbl
或CSng
(根据您的要求)将每个子字符串转换为数字然后添加数字。
以下是一个例子:
Dim inputStr As String
inputStr = "1.5, 2, 3, 5"
Dim arr() As String
arr = Split(inputStr, ",")
Dim total As Single ' Or `Double` if you need more accuracy.
For Each subStr In arr
total = total + Val(subStr) ' Use `Val` if you want to ignore non-numeric values.
'total = total + CSng(subStr) ' Use `CSng` to break when finding non-numeric values.
'total = total + CDbl(subStr) ' Use `CDbl` if you need more accuracy.
Next
MsgBox total