What to do when autofilter in VBA returns no data?

后端 未结 5 1747
北恋
北恋 2020-12-19 08:51

I am trying to filter a range of values and based on my criteria, at times I might have no data that fits my criteria. In that case, I do not want to copy any data from the

5条回答
  •  遥遥无期
    2020-12-19 09:16

    since you use myRange as the real output of the filtering action you could go like follows

    Dim wbKGRR As Workbook  '<== better set variable for workbooks you'll work with: it saves both typing time and possible errors
    Dim ws As Worksheet  '<== better set variable for worksheets you'll work with: it saves both typing time and possible errors
    
    '...
    
    
    Set wbKGRR = Workbooks(KGRReport) '<== better set variable for workbooks: it saves both typing time and possible errors
    Set ws = wbKGRR.Worksheets(spreadSheetName)  '<== better set variable for worksheets you'll work with: it saves both typing time and possible errors
    
    With ws
        With .Range("A1:I" & lastrowinSpreadSheet)
            .AutoFilter Field:=3, Criteria1:=LimitCriteria, Operator:=xlFilterValues 'Do the filtering for Limit
            .AutoFilter Field:=9, Criteria1:=UtilizationCriteria, Operator:=xlFilterValues 'Do the filtering for Bank/NonBank
        End With
        If Application.WorksheetFunction.Subtotal(103, .Columns("B")) > 0 Then Set myRange = .Range("B2:H" & lastrowinSpreadSheet).SpecialCells(xlVisible) '<== myRange will be set only if filtering has left some visible cells
    End With
    
    
    'Clear the template
    'Workbooks(mainwb).Worksheets("Template").Activate '<== no need to activate
    Workbooks(mainwb).Worksheets("Template").Rows(7 & ":" & Rows.Count).Delete
    
    'Copy the filtered data
    ' Workbooks(KGRReport).Activate '<== no need to activate
    If Not myRange Is Nothing Then '<== "myRange" has been set properly if previous Autofilter method has left some visbile cells
        For Each myArea In myRange.Areas
            For Each rw In myArea.Rows
                  strFltrdRng = strFltrdRng & rw.Address & ","
            Next rw
        Next myArea
    
        strFltrdRng = Left(strFltrdRng, Len(strFltrdRng) - 1)
        Set myFltrdRange = Range(strFltrdRng)
        myFltrdRange.Copy
        strFltrdRng = ""
    End If
    

    where I also suggested some workbook and worksheet variable settings to "ease" coding life

提交回复
热议问题