簡體   English   中英

做COUNTIF,但包括合並的單元格

[英]Doing what COUNTIF does, but including merged cells

是的,我知道,合並的單元格不好,但是出於美學原因,我需要它們!

我有一堆牢房,上面貼有標簽(簡短的文字)。 我想計算每個標記在定義范圍內存在多少次。 這樣做很容易,但是美學影響卻很大。 如果我將它們合並,所有的外觀都很好,但是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並沒有成功。 有什么建議嗎?

像這樣:

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的問題。

請嘗試以下代碼:

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方法-每個...下一個

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM