countif使用自动过滤器更改多列

时间:2018-10-17 12:50:40

标签: excel vba excel-vba

我正在研究VBA项目,我希望它计算与特定条件匹配的范围内的单元数。

两列也是,如果满足两个要求,则countif将对值进行计数。 另外,我在范围内添加了自动过滤器,因此当您对列进行过滤时,计数将发生变化(例如,如果我选择某个教室而不是全部教室,则值将发生变化)

        dim i as integer
    dim rcell as integer
    lastrow = Activesheet.Cells(.Rows.Count, 1).End(xlUp).Row

Col_Dessert =5
Col_Snack =6

i=0

    with Worksheets("JIS")
For rcell = 1 to lastrow
If range(cells(rcell,Col_Dessert).value="L" ) And range(cells(rcell,Col_Dessert).value="WESTERN" ) then
i=i+1

end if
next rcell
end with

4 个答案:

答案 0 :(得分:1)

如果该确实需要在VBA中使用-我可以想到可能发生的各种情况-那么您可以使用Range.SpecialCells(xlCellTypeVisible)来获取 only 可见的单元格-例如

Dim Col_Dessert As Long, Col_Snack As Long

Dim i As Long
Dim rowCheck As Range, wsCheck As Worksheet

Col_Dessert = 5
Col_Snack = 6

i = 0
Set wsCheck = Worksheets("JIS")
For Each rowCheck In Intersect(wsCheck.AutoFilter.Range.Columns(1), wsCheck.AutoFilter.Range.SpecialCells(xlCellTypeVisible)).Cells
    If wsCheck.Cells(rowCheck.Row, Col_Dessert).Value = "L" And wsCheck.Cells(rowCheck.Row, Col_Dessert).Value = "WESTERN" Then
        i = i + 1
    End If
Next rowCheck

Set wsCheck = Nothing

但是,如果您试图创建用户定义函数来在工作表中执行此操作,请考虑使用SUMPRODUCTSUBTOTAL(103(即COUNTA而不考虑隐藏的行)。基本形式:

=SUMPRODUCT(--(ConditionRange1="Value1")*--(ConditionRange2="Value2")*--SUBTOTAL(103,OFFSET($A$1,ROW(ConditionRange1)-1,0)))

适合您,以匹配E列中的"L"和F列中的"WESTERN"

=SUMPRODUCT(--($E$1:$E$100="L")*--($F$1:$F$100="WESTERN")*--SUBTOTAL(103,OFFSET($A$1,ROW($A$1:$A$100)-1,0)))

答案 1 :(得分:0)

Dim i As Integer
Dim r As Range
Dim wsCheck As Worksheet

i = 0
Set wsCheck = Worksheets("JIS")
For Each r In Intersect(wsCheck.AutoFilter.Range.Columns(5), wsCheck.AutoFilter.Range.SpecialCells(xlCellTypeVisible)).Cells
    If wsCheck.Cells(r.Row, Col_Starter).Value = "S" And wsCheck.Cells(r.Row, Col_Dessert).Value = "WESTERN" Then
        i = i + 1
        wsCheck.Range("A5") = "S:" & " " & i
    End If
Next r

答案 2 :(得分:0)

Dim i As Long 
Dim r As Range
 Dim wsCheck As Worksheet 
i = 0 
Set wsCheck = Worksheets("JIS")
 wsCheck.Application.Volatile (True) 
For Each r In Intersect(wsCheck.AutoFilter.Range.Columns(Col_Western), wsCheck.AutoFilter.Range.SpecialCells(xlCellTypeVisible)).Cells
If wsCheck.Cells(r.Row, Col_Starter).Value = "S" And wsCheck.Cells(r.Row, Col_Dessert).Value = "WESTERN" Then i = i + 1 wsCheck.Range("A5") = "S:" & " " & i 
End If 
Next r 
Set wsCheck = Nothing

答案 3 :(得分:0)

您不需要VBA。使用Excel智能公式。

  

=SUMPRODUCT(SUBTOTAL(3,OFFSET(EDIManifestsAll[UniqueContainer], ROW(EDIManifestsAll[UniqueContainer])-ROW(EDIManifestsAll[UniqueContainer]),0,1)), --(EDIManifestsAll[UniqueContainer]="Y"))

位置:

  • EDIManifestsAll =您的表引用或名称
  • UniqueContainer =您过滤后的列标题
  • “ Y” =您想要COUNTIF()
  • 的任意值

ps:我的回答是基于您的标题“用自动过滤器更改计数...” 。如果您要专门在VBA中解决问题,则所有其他答案都应该解决。