We help IT Professionals succeed at work.

VBA to autofilter in a specific column for each criteria and copy the result to a new sheet

kishore naidu
Need to filter on each region (Column F) and copy the result to a new worksheet. would be helpful if this can be done through looping as the original data set contains more regions. Thanks for the help

Watch Question

Excel & VBA Expert
Most Valuable Expert 2018
Awarded 2015
Your file link is broken. Why didn't you upload the file here itself?

Anyways please find attached a sample workbook with some dummy data along with a button on Sheet1 and code on Module1.
Please click the button to run the code. The code will copy the data for all the regions to their respective sheets.
Sub FilterByRegionAndCopyData()
Dim sws As Worksheet, dws As Worksheet
Dim dict, it, x
Dim lr As Long, i As Long
Application.ScreenUpdating = False
Set sws = Sheets("Sheet1")  'Sheet which contains data for all the regions
lr = sws.Cells(Rows.Count, 6).End(xlUp).Row
x = sws.Range("F2:F" & lr).Value
Set dict = CreateObject("Scripting.Dictionary")
For i = 1 To UBound(x, 1)
   dict.Item(x(i, 1)) = ""
Next i
For Each it In dict.keys
   With sws.Range("A1").CurrentRegion
      .AutoFilter field:=6, Criteria1:=it
      On Error Resume Next
      Set dws = Sheets(it)
      On Error GoTo 0
      If dws Is Nothing Then
         Sheets.Add(after:=Sheets(Sheets.Count)).Name = it
         Set dws = ActiveSheet
      End If
      sws.Range("A1").CurrentRegion.SpecialCells(xlCellTypeVisible).Copy dws.Range("A1")
   End With
   Set dws = Nothing
Next it
Application.ScreenUpdating = False
MsgBox "Data for all the regions has been copied to their respective region sheet successfully.", vbInformation, "Done!"
End Sub

Open in new window



Thanks a lot. This is more than what i expected.i shall change the code to suit to the actual data.
Subodh Tiwari (Neeraj)Excel & VBA Expert
Most Valuable Expert 2018
Awarded 2015

You're welcome Kishore! Glad to help.