正如标题所示,我正在寻找一种方法来从单元格注释中检索所有数字并将其加起来。我能想到的唯一方法是将注释检索为字符串,将每个数字集分配给一个变量,然后将这些变量加起来?
我很难理解逻辑,我不知道一种从注释中检索数字的方法。
到目前为止,我有:
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等...”我希望在新列表生成时随时更新该单元格值反映总费用。有道理吗?
答案 0 :(得分:2)
在不对数字做任何假设的情况下,我将使用正则表达式来提取数字,然后将它们加起来。我使用了发现的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
答案 1 :(得分:1)
我的以下代码在以下假设下工作: -
注意:用“ 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