【问题标题】:How to count only visible cells in a custom function (count cells based on cell colour)如何仅计算自定义函数中的可见单元格(根据单元格颜色计算单元格)
【发布时间】:2020-02-07 13:16:45
【问题描述】:

我正在使用我在网上找到的自定义函数。它完成了我需要它做的事情 - 计算一系列单元格中特定颜色的单元格。

如何编辑它以仅计算可见单元格? 我曾尝试使用它,但它没有任何作用。

For Each rCell In CountRange.SpecialCells(xlCellTypeVisible)

完整的功能是这样的:

    Function GetColorCount(CountRange As Range, CountColor As Range, Optional VolatileParameter As Variant)
Dim CountColorValue As Integer
Dim TotalCount As Integer
CountColorValue = CountColor.Interior.ColorIndex
Set rCell = CountRange
For Each rCell In CountRange
  If rCell.Interior.ColorIndex = CountColorValue Then
    TotalCount = TotalCount + 1
  End If
Next rCell
GetColorCount = TotalCount
End Function

要在工作表中使用它,然后输入:

=GetColorCount(A1:G20,H1, NOW())

地点:

  • A1:G20 是我要统计所有黄色单元格的范围
  • H1 是显示计数的单元格,颜色为黄色
  • NOW() 让它在每次在范围内进行更改时运行 (??)

有什么建议吗?

【问题讨论】:

  • 我相信 SpecialCells 不会在 UDF 中工作

标签: excel vba


【解决方案1】:
Function GetColorCount(CountRange As Range, CountColor As Range, Optional VolatileParameter As Variant)
 Dim ColVal As Long, rCell As Range
 Dim TotalCount As Long
 ColVal = CountColor.Interior.ColorIndex
    For Each rCell In CountRange.Cells
      If rCell.Interior.ColorIndex = ColVal Then
          If rCell.EntireRow.Hidden = False And _
              rCell.EntireColumn.Hidden = False Then
              TotalCount = TotalCount + 1
          End If
      End If
    Next rCell
 GetColorCount = TotalCount
End Function

SpecialCells 不能在 UDF 中使用,但可以检查范围可见性中的每个单元格...

【讨论】:

  • 很棒的解决方案 FaneDuru!工作一种享受!感谢您花时间回答
  • 欢迎您!但是@CLR 发布的解决方案也应该有效。这是一个有趣的解决方法...... Ups。直到现在我才能看到你(在某种程度上)证实了这一点:)
  • 这与我之前的回答基本相同。但我只是想知道为什么您将 OPs CountColorValue(您的 ColVal)切换为 Long?作为.Colorindex,它只需要一个整数,因为它是 0 到 56。
  • 保持整数没有任何好处,不,但是在更改它时可能会给 OP 造成混淆?当我们有幸实际获得 OP 现有代码时,我会尝试只更改那些需要它的部分。
【解决方案2】:

SpecialCells 在像这样包裹在 UDF 中时确实是片状的。

这是通过检查行高和列宽为零的解决方案/解决方法。我确定其他人存在,但这是实现目标的一种方式。

Function GetColorCount(CountRange As Range, CountColor As Range, Optional VolatileParameter As Variant)
    Dim CountColorValue As Integer
    Dim TotalCount As Integer
    CountColorValue = CountColor.Interior.ColorIndex
    For Each rcell In CountRange.Cells
        If rcell.Interior.ColorIndex = CountColorValue Then
            If (rcell.EntireRow.Height * rcell.EntireColumn.Width) <> 0 Then
                TotalCount = TotalCount + 1
            End If
        End If
    Next rcell
    GetColorCount = TotalCount
End Function

【讨论】:

  • 感谢 CRL。这和我收到的其他答案一样有效。希望这对这个小组的其他成员有用:)
猜你喜欢
  • 2016-11-17
  • 2023-02-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-15
  • 1970-01-01
相关资源
最近更新 更多