VBA-计算隐藏并具有特定值的单元格

时间:2019-01-09 13:28:07

标签: excel vba hidden countif

我试图弄清楚如何编写VBA代码,该代码可以计算我范围内隐藏的单元格并具有特定值。

我已经尝试过类似的方法,但是它不起作用:

Sub Count_hidden_ABC()
Dim s As Long
Dim Rg As Range
Set Rg = Worksheets("Sheet1").Range("G8:G255")
s = Application.WorksheetFunction.CountIfs(Rg, "ABC", Rg, SpecialValues(12))

Sub Count_hidden_ABC()
Dim s As Long
Dim Rg As Range
Set Rg = Worksheets("Sheet1").Range("G8:G255")
s = Rg.SpecialCells(12).Application.WorksheetFunction.CountIf(Rg, "ABC")

有人知道如何执行此操作吗?

2 个答案:

答案 0 :(得分:2)

特殊细胞专长。区域

  • 选择SpecialCells( 12 )或 SpecialCells( xlCellTypeVisible ),您正在选择可见 单元格不是您所需的隐形对象。
  • 完全不知道发生了什么,但似乎是 CountIf 不适用于非连续范围。
  • 因此您可以使用以下方法遍历非连续范围内的范围 区域

代码

Sub Count_hidden_ABC()

    Dim s As Long
    Dim Rg As Range
    Dim rng As Range
    Set Rg = Worksheets("Sheet1").Range("G8:G255")

    For Each rng In Rg.SpecialCells(12).Areas
        s = s + WorksheetFunction.CountIf(rng, "ABC")
    Next

    s = WorksheetFunction.CountIf(Rg, "ABC") - s
    'Debug.Print s

End Sub

答案 1 :(得分:0)

您可以将此代码用作基础,它可以计算指定范围内值为"ABC"的隐藏单元格:

Sub CountHiddenCellsInRange()
    Dim rng As Range, hiddenCells As Long, c As Range
    hiddenCells = 0
    Set rng = Range("A1:B5")
    For Each c In rng
        If (Rows(c.Row).Hidden Or Columns(c.Column).Hidden) And c.Value = "ABC" Then hiddenCells = hiddenCells + 1
    Next
    MsgBox hiddenCells
End Sub