vba在过滤

时间:2017-10-08 11:29:18

标签: vba filter count

Sub test_calculateval() 
    Dim rnData, r As Range, ThisYearID, LR, FR, EndR, HomeCount, AwayCount, DrawCount, i As Long, Hometeam As String 
    ThisYearID = Sheet5.Cells(2, 1).Value - 1 
    Hometeam = Sheet5.Cells(2, 5) 
    HomeCount = 0 
    With Sheet1
        Set rnData = Range(Range("A2"), Range("R2").End(xlDown))
        With rnData
            Rows("1:1").Select
            Selection.AutoFilter
            ActiveSheet.Range(Range("A2"), Range("R2").End(xlDown)).AutoFilter Field:=1, Criteria1:=">" & ThisYearID - 5
            ActiveSheet.Range(Range("A2"), Range("R2").End(xlDown)).AutoFilter Field:=5, Criteria1:=Hometeam
            LR = Range("A" & Rows.count).End(xlUp).Row
            Set r = ActiveSheet.Range("A2:R" & LR).Rows.SpecialCells(xlCellTypeVisible)
            FR = r.Row
            EndR = Range("A" & FR).End(xlDown).Row 
            For Each rngarea In .SpecialCells(xlCellTypeVisible).Areas
                If Range("K2:K" & LR).SpecialCells(xlCellTypeVisible).Value = "H" Then
                    HomeCount = HomeCount + 1
                End If 
            Next
        End With 
    End With 
    MsgBox HomeCount 
End Sub

我想检查列K中的每个单元格(过滤后)是否等于“H”,并计算它们。 这段代码抛出了类型不匹配错误,似乎是问题

1 个答案:

答案 0 :(得分:0)

因为有可能

    Range("K2:K" & LR).SpecialCells(xlCellTypeVisible).Value

可能会返回多个单元格,因此无法将其与单个字符串值进行比较。简单来说,当它们返回到一个范围时,我们无法计算多个单元格的值。该解决方案将第三个过滤器应用于过滤范围,该过滤范围过滤所有具有值" H"在K列中,然后我们计算所有可见细胞。

这段代码会比通过循环做同样的事情更快。

用以下代码替换现有代码:

Sub test_calculateval() 
Dim rnData, r As Range, ThisYearID, LR, FR, EndR, HomeCount, AwayCount, DrawCount, i As Long, Hometeam As String 
ThisYearID = Sheet5.Cells(2, 1).Value - 1 
Hometeam = Sheet5.Cells(2, 5) 
HomeCount = 0 
With Sheet1
    Set rnData = Range(Range("A2"), Range("R2").End(xlDown))
    With rnData
        .AutoFilter 
        .AutoFilter Field:=1, Criteria1:=">" & ThisYearID - 5
        .AutoFilter Field:=5, Criteria1:=Hometeam
        .AutoFilter Field:=11, Criteria1:="=H", Operator:=xlAnd
        HomeCount = .Columns("K2:K" & (rnData.Rows.Count)).SpecialCells(xlCellTypeVisible).Count-1
    End With 
End With 
MsgBox HomeCount 

End Sub