excel 应用筛选后对空白单元格计数

jq6vz3qz  于 2023-03-04  发布在  其他
关注(0)|答案(1)|浏览(201)

这段代码计算了E列中的空白单元格,所以逻辑是正确的。但是,在计算空白单元格之前,我想从H列中排除“Cash”。
该代码确实对列H(不包括现金)应用了过滤器,但是对于包括现金的数据,空白单元格也会被计入。

Sub exampleTHis()

    ActiveSheet.Range("H:H").AutoFilter Field:=8, Criteria1:="<>Cash", _
    Operator:=xlAnd

Dim ws As Worksheet, testRange As Range, aCount As Long, zAnswer

For Each ws In ThisWorkbook.Worksheets

Set testRange = Intersect(ws.Range("E:E"), ws.UsedRange)
 'Set testRange = ws.Range("E2", Range("E" & Rows.Count).End(xlUp)).SpecialCells(xlCellTypeVisible)
 
    If Not testRange Is Nothing Then
        
        aCount = Application.WorksheetFunction.CountBlank(testRange)
        If aCount > 0 Then
         'blank cells found....
            zAnswer = MsgBox(aCount & " blank values found in at " & ws.Name & testRange.Address & ".  Continue macro?", vbYesNo)
            
            If zAnswer = vbNo Then Exit For
            
        End If
    End If
    
Next ws

End Sub
wfauudbj

wfauudbj1#

使用AutoFilterSpecialCells对自动过滤微柱中的空白进行计数

  • 为了能够在消息框中写入关键单元格的地址,复杂性是必要的。如果你只是在计数之后,你可以简化。
Sub CountBlanksInFilteredColumn()
    ' Not blank:           "<>"
    ' Blank:               "" or "=" (includes Empty)
    ' Blank but not empty: "<=>"
    ' Empty?
    
    Const SHEET_NAME As String = "Assets"
    Const BLANK_COLUMN As Long = 5
    Const BLANK_CRITERION As String = ""
    Const CASH_COLUMN As Long = 8
    Const CASH_CRITERION As String = "<>Cash"
    
    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
    Dim ws As Worksheet: Set ws = wb.Sheets(SHEET_NAME)
    
    Dim vrg As Range
    
    With ws
        If .FilterMode Then .ShowAllData ' clear filters
        Dim rg As Range: Set rg = ws.UsedRange
        Dim crg As Range ' without header
        With rg
            Set crg = .Columns(BLANK_COLUMN).Resize(.Rows.Count - 1).Offset(1)
            .AutoFilter BLANK_COLUMN, BLANK_CRITERION
            .AutoFilter CASH_COLUMN, CASH_CRITERION
        End With
        On Error Resume Next
            Set vrg = crg.SpecialCells(xlCellTypeVisible)
        On Error GoTo 0
        .AutoFilterMode = False ' turn off auto filter
    End With
    
    Dim Blanks As Long, vrgAddress As String
    
    If Not vrg Is Nothing _
        Then Blanks = vrg.Cells.Count: vrgAddress = vrg.Address(0, 0)
    
    MsgBox "Found " & Blanks & " blank cell" _
        & IIf(Blanks = 1, "", "s") _
        & IIf(Blanks = 0, ".", ":" & vbLf & vrgAddress), _
        IIf(Blanks = 0, vbExclamation, vbInformation)
    
End Sub

如果没有空白单元格则继续

End With
    
    If Not vrg Is Nothing Then
        MsgBox "Found " & vrg.Cells.Count & " blank cell" _
            & IIf(Blanks = 1, "", "s") & ":" & vbLf & vrg.Address(0, 0), _
            vbExclamation
        Exit Sub
    End If
    
    ' No blanks found, continue with your code.

End Sub

相关问题