【问题标题】:Extract numbers from comment and add them从评论中提取数字并添加它们
【发布时间】:2020-07-08 03:52:13
【问题描述】:

正如标题所示,我正在寻找一种方法来从单元格注释中检索所有数字并将它们相加。我能想到的唯一方法是将注释作为字符串检索,将每组数字分配给一个变量,然后将变量相加?

我很难理解逻辑,我不知道如何从评论中检索数字。

到目前为止我有:

Private Sub Worksheet_Change(ByVal Target As Range)
Dim varComment As String
For i = 19 To 30
If Not Intersect(Target, Range("N19:N30")) Is Nothing Then
    On Error Resume Next
    varComment = Cells(Ni).Comment.Text
    Next i
End If
End Sub

用途是我在单元格 N19:N30 中有一条评论,其中包含美元值,“食物 - 20 美元,汽油 - 40 美元等...”反映总成本。有意义吗?

【问题讨论】:

  • 向我们展示您的尝试。

标签: excel vba


【解决方案1】:

在不对数字做任何假设的情况下,我将使用正则表达式提取数字,然后将它们相加。我使用了一个找到here的函数并稍作修改。

Function CleanString(strIn As String) As String
Dim objRegex
    Set objRegex = CreateObject("vbscript.regexp")
    With objRegex
        .Global = True
        '.Pattern = "[^\d]+"
        .Pattern = "[^0-9" & Application.DecimalSeparator & "]"
        CleanString = .Replace(strIn, vbCrLf)
    End With
End Function

使用此功能,您可以将评论中的数字相加

Function commentSum(cmt As Comment) As Double

Dim vDat As Variant
Dim i As Long
Dim res As Double

    vDat = Split(CleanString(cmt.Text), vbCrLf)
    For i = LBound(vDat) To UBound(vDat)
        If Len(vDat(i)) > 0 Then
            res = res + CDbl(vDat(i))
        End If
    Next i
    commentSum = res
End Function

用于测试目的

Sub TestCmtAdd()
Dim rg As Range
Dim sngCell As Range

Set rg = Range("A1:A10")

For Each sngCell In rg
    If Not (sngCell.Comment Is Nothing) Then
        MsgBox "Sum of numbers in comment of cell: " & sngCell.Address & " is " & commentSum(sngCell.Comment)
    End If
Next

End Sub

【讨论】:

  • 一切似乎都运行良好,有没有办法在单元格注释更改时启动此宏?目前它被设置为选择更改,但这有明显的缺点。
  • 这可能值得提出一个新问题。我不知道如何监视评论中的更改的简短答案。也许在关闭或保存文档之前运行宏就足够了。
【解决方案2】:

我的以下代码在以下假设下工作:- -

  • 每个数字必须以“$”开头($ 和数字之间的空格将被删减)
  • 每个数字必须以“,”结尾(“,”之间的空格并且数字将被修剪)
  • 您的“varComment”已填充

注意:用“vbCrLf”拆分评论对我不起作用

Dim SplitedComment() As String
Dim tmpStr As Variant
Dim DolarSignLoc, yourSum As Integer

' For Each Comment, Do the following
SplitedComment() = Split(varComment, ",")   ' Split the Comment by ",", we'll need ONLY the output that Contain "$" ( some of the output may NOT contain that char)

yourSum = 0     ' initialize your Sum Variable
For Each tmpStr In SplitedComment  ' for each Text in the SplittedComment
    DolarSignLoc = InStr(tmpStr, "$")   ' Get the Location of the "$" ( ZERO if not exist)
    If DolarSignLoc > 0 Then            ' ONLY Process the Text if contains "$"
        tmpStr = Right(tmpStr, Len(tmpStr) - DolarSignLoc)  ' Excetract your Number
        yourSum = yourSum + CInt(Trim(tmpStr))              ' Add to your Summation
    End If
Next

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-10
    • 1970-01-01
    • 1970-01-01
    • 2014-04-25
    • 2016-08-18
    • 1970-01-01
    • 2018-07-30
    相关资源
    最近更新 更多