Excel计数样式和文本内容

时间:2018-10-13 06:02:15

标签: excel vba

我对Excel的VBA还是很陌生,并且已经在网上搜索了此特定问题。也许是因为我是编码的新手,答案对我来说并不突出,但在这里。

最初,我想使用一个公式来计算范围内的样式。之后,我想返回在相同样式范围内包含特定文本的单元格数。

例如,列表的样式可以是好,坏或普通。另外,它将有Bob,Joe或Jane。在另一个地方,我将尝试计算单词“ Bob”以“ Good”样式出现的次数,并将其作为值返回。如果“鲍勃”总共显示10次,但其中只有4次被设置为“好”,则计数将返回“ 4”。此外,如果样式“ Good”出现5次,但其中只有4个样式中包含文本“ Bob”,则计数将返回“ 4”。

我为此有两个公式,但是它们仅返回特定文本的计数或特定样式的计数。另外,我想指定仅在公式中而不是在VBA模块中计数的文本。

VAR = CountStyleAndText(“ Bob”,B2:B26) 通过单元格B2和B26中的“好”样式计数“鲍勃”

这是我遇到的第一个代码,它计算单元格范围内的样式

Function CountStyleGood(CellRange)
  Dim Item As Range, Total As Long
    For Each Item In CellRange
    ' Check to see if the cell is formatted as Style = "Good"
       If Item.Style = "Good" Then
          Total = Total + 1
       End If
     Next Item
        CountStyleGood = Total
     End Function

这是我遇到的第二个代码,它对单元格范围内的文本进行计数(已测试,但未能使其正常工作)

= count(“找到我”,Range(“ A1:A100”))

function count(find as string, lookin as range) As Long
   dim cell As Range
   for each cell in lookin
      if (cell.Value = find) then 
         count = count + 1 '//case sens
    next
 end function

我想像这样:

Function CountStyleAndText(CellRange, find As String, lookin As Range) As Long
   Dim Item As Range, Total As Long, Cell As Range 
   For Each Item In CellRange
      ' Check to see if the cell is formatted as Style = "Good"
      If Item.Style = "Good" And (cell.Value = find) Then
          Total = Total + 1
      End If
    Next Item
    CountStyleAndText = Total
 End Function

请记住,这是您在要计数的单元格中键入的内容:

= CountStyleAndText(“ Bob”,B1:B26)

1 个答案:

答案 0 :(得分:0)

如果您想在“公式”中(即在UDF调用中)指定样式名称,请使用:

Function CountStyleGood(find As String, lookin As Range, styleName As String)
    Dim Item As Range, Total As Long

    For Each Item In lookin
        If Item.Style = styleName Then If Item.Value = find Then Total = Total + 1
    Next Item
    CountStyleGood = Total
End Function

如果要对样式名称进行硬编码:

Function CountStyleGood(find As String, lookin As Range)
    Dim Item As Range, Total As Long

    For Each Item In lookin
        If Item.Style = "Good" Then If Item.Value = find Then Total = Total + 1
    Next Item
    CountStyleGood = Total
End Function

这两种情况都请记住,样式名称区分大小写(即“好”与“好”不同)