excel - 解析字符串并对正负数字分量求和

标签 excel excel-formula vba

我在 Excel 单元格中有一个字符串。

每行代表一个句子。此字符串表示句子中单词的正负分。

句子可以是任意长度,例如

joy: pos=0.37 neg=0.0, honest: pos=0.4 neg=0.0, pick: pos=0.0 neg=0.0
hello: pos=0.0 neg=0.0, ok: pos=0.0 neg=0.0



我想计算单元格中的总正负数。

如果不将字符串与 Excel 中的文本分列功能分开,我不知道用公式执行此操作的可能方法。

在这种情况下,输出的一个示例是:

pos=0.77 neg=0.0
pos=0.0 neg=0.0



有任何想法吗?

最佳答案

可能有更好的方法,但我相信这对你有用:

Function pos(rTest As Range) As String

Dim a() As String
Dim i As Integer
Dim iVal As Double
Dim wf As WorksheetFunction
Set wf = Application.WorksheetFunction

a = Split(rTest, ",")

Dim iStart As Integer
Dim iEnd As Integer

For i = LBound(a) To UBound(a)
    iStart = wf.Find("=", a(i)) + 1
    iEnd = InStr(wf.Find("=", a(i)) + 1, a(i), " ")
     iVal = iVal + CDbl(Mid(a(i), iStart, iEnd - iStart))
Next

pos = "pos=" & CStr(iVal)

End Function

Function neg(rTest As Range) As String

Dim a() As String
Dim i As Integer
Dim iVal As Double
Dim wf As WorksheetFunction
Set wf = Application.WorksheetFunction

a = Split(rTest, ",")

Dim iStart As Integer
Dim iEnd As Integer

For i = LBound(a) To UBound(a)
    iStart = InStrRev(a(i), "=") + 1
    iEnd = Len(a(i)) + 1
    iVal = iVal + CDbl(Mid(a(i), iStart, iEnd - iStart))
Next

neg = "neg=" & CStr(iVal)

End Function

我仍然认为自己是 VBA 的新手。我相信它可以优化或收紧一点。将这两个函数放在一个 VBA 模块中。然后把 =pos=neg相应地作为单元格中的常规公式并将范围放入。

关于excel - 解析字符串并对正负数字分量求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37114061/

相关文章:

使用 VBA 将未修改的 Excel 工作簿检入 SharePoint 时 Excel 崩溃

Excel 错误,停止运行宏

excel - 在 excel 2013 中有条件地重复公式?

excel - 如何阻止excel更改单元格内的公式?

excel - 在 VBA 函数中使用带有变量的单元格值

excel - vba 使用 CHR(34) 在单元格内容周围添加引号会引发 "sub not defined"错误

c# - 如何在 Excel Interop C# 中读取日期时间

excel - 根据单元格值动态更新 SUM 范围

vba - 如何在同一工作表Excel VBA中复制列

excel - 使用 VBA 中的 Replace 方法将数字存储为字符串