Autofilter to include Headers

I have a excel file with template which look something like this. enter image description here

I am trying to filter down records based on customer ID column and create PDF's . I am using below VBA code to do the job.

Public Sub Create_PDFs()

    Dim CustomerIDsDict As Object, CustomerID As Variant
    Dim r As Long
    Dim currentAutoFilterMode As Boolean
    
    Set CustomerIDsDict = CreateObject("Scripting.Dictionary")
    
    'The code looks at data on the active sheet
    
    With ActiveSheet
    
        'Save current UI autofilter mode
        
        currentAutoFilterMode = .AutoFilterMode
        
        If currentAutoFilterMode Then .AutoFilter.ShowAllData
       
        'Create dictionary containing unique Customer IDs (column B) and associated Country (column B), keyed on Customer ID
        
        For r = 5 To .Cells(.Rows.Count, "B").End(xlUp).Row
            CustomerIDsDict(.Cells(r, "B").Value) = .Cells(r, "C").Value
        Next
        
        'For each unique Customer ID
        
        For Each CustomerID In CustomerIDsDict.keys
            
            'AutoFilter on column B (Field:=2) with this Customer ID
            
            .UsedRange.AutoFilter Field:=2, Criteria1:=CustomerID
        
            'Save filtered data as PDF file "<Customer ID> <Country>.pdf" in same folder as this workbook
            
            .ExportAsFixedFormat Type:=xlTypePDF, Filename:=ThisWorkbook.Path & "\" & CustomerID & " " & CustomerIDsDict(CustomerID) & ".pdf", _
                Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
                    
        Next
    
        'Restore previous autofilter, if any
    
        If currentAutoFilterMode Then
            .AutoFilter.ShowAllData
        Else
            .AutoFilterMode = False
        End If
        
    End With
    
End Sub

It filters down based on customer id correctly and creating PDF's.But the rows 2,3,4 are missing from the pdf's created. It has only the 1st row then the filtered values.

Can anyone help me with this.


Instead of autofiltering the used range starting from row one as in your example, I'd

  • a) define the filtering top cell explicitly at cell A3 to get the header fields and
  • b) unhide the entire hidden row following the header fields (here with translated title notes)

e.g. like this

            'AutoFilter on column B (Field:=2) with this Customer ID
'            .UsedRange.AutoFilter Field:=2, Criteria1:=CustomerID
             With .Range("A3")
                .AutoFilter Field:=2, Criteria1:=CustomerID
                .Rows(2).EntireRow.Hidden = False
             End With
         'further stuff ...