计算注释中string的出现次数

我刚开始在excel中尝试一些VBA,我正在计算select的注释中某个单词的出现次数。 以下是我到目前为止:

Function CountStringInComments(strText As String, ByVal Target As Range) As Long Dim c As Comment Dim n As Long For Each c In Target.Comments n = n - (InStr(1, c.Text, strText, vbTextCompare) > 0) Next CountStringInComments = n Set c = Nothing End Function 

并调用我的函数应该看起来像:

 =CountStringInComments("bruit",Z55:Z58) 

我有一个#VALUE! 错误。

我不熟悉VB,所以任何帮助表示赞赏。 谢谢。

您需要提取单元格而不是注释,然后search该单元格的注释文本。

 Function CountStringInComments(strText As String, ByVal Target As Range) As Long Dim c As Range Dim n As Long For Each c In Target.Cells If Not c.Comment Is Nothing Then n = n - (InStr(1, c.Comment.Text, strText, vbTextCompare) > 0) End If Next CountStringInComments = n Set c = Nothing End Function 

在这里输入图像描述

如果你想统计所有比赛(包括多次在一个评论),那么你可以这样做:

 Function CountStringInComments(str As String, ByVal r As Range) As Long Dim re As RegExp Set re = New RegExp re.Global = True re.Pattern = str re.IgnoreCase = True Dim cell As Range For Each cell In r If Not cell.Comment Is Nothing Then Dim mColl As MatchCollection Set mColl = re.Execute(cell.Comment.Text) CountStringInComments = CountStringInComments + mColl.Count End If Next cell End Function 

需要引用Microsoft VBScript正则expression式5.5