做COUNTIF,但包括合并的单元格

时间:2019-01-01 21:29:41

标签: excel vba excel-vba

是的,我知道,合并的单元格不好,但是出于美学原因,我需要它们!

我有一堆牢房上贴有标签(简短的文字);我想计算每个标记在定义范围内存在多少次。这样做很容易,但是美学影响却很大。如果我将它们合并,那么所有的外观都很好,但是countif不再有用,因为它将整个单元格视为一个。

我一直在尝试找出如何使用vba模块做我想做的事,但是我为此感到很糟糕。

这给了我第一个具有要搜索的字符串的单元格的单元格数。

Function dcounter(r As Range, s As String) As Integer
   dcounter = 0
   If Not r.Find(s) Is Nothing Then dcounter = r.Find(s).MergeArea.Cells.Count
End Function

我只需要弄清楚如何在整个范围内进行循环。我一直在尝试与For Each并没有成功。有什么建议吗?

2 个答案:

答案 0 :(得分:0)

类似这样的东西:

Function CountMerged(rng As Range, txt As String)
    Dim col As Collection, n As Long, c
    Set col = FindAll(rng, txt)
    For Each c In col
        n = n + c.MergeArea.Count
    Next c
    CountMerged = n
End Function

Public Function FindAll(rng As Range, val As String) As Collection

    Dim rv As New Collection, f As Range
    Dim addr As String

    Debug.Print rng.Cells.Count

    Set f = rng.Find(what:=val, after:=rng.Cells(rng.Cells.Count), _
        LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows, _
        SearchDirection:=xlNext)

    If Not f Is Nothing Then addr = f.Address()

    Do Until f Is Nothing
        Debug.Print f.Address
        rv.Add f
        'Note: FindNext() won't work in a UDF
        Set f = rng.Find(what:=val, after:=f)
        If f.Address() = addr Then Exit Do
    Loop

    Set FindAll = rv
End Function

注意-合并/取消合并不会触发UDF的重新计算,即使您添加Application.Volatile也不清楚,虽然从您的问题中不清楚您是否正在寻找UDF。

答案 1 :(得分:0)

请尝试以下代码:

Function dcounter(r As Range, s As String) As Integer
  Dim c As Range
  For Each c In r
    If c.Value = s Then
      dcounter = dcounter + c.MergeArea.Count
    End If
  Next
End Function

参考:Range.Find method - For Each...Next