excelvba

Add a rule to the VBA to remove filters


I have a code to copy data bewteen two different workbooks while the source file is closed and it's working perfectly but with one problem which is when the source file is closed with active filters in the table i get a problem in the data copied to the destination file

So, what I need is to add a rule to the code to clear all filters in the soruce file "stop work" before copying the data so that all data can be transfered to the destination file

and here is my code

Sub Update()

  ' Open the source workbook
Set sourceWorkbook = Workbooks.Open(Filename:="D:\Desktop\Stop Work.xlsm")

sourceWorkbook.Worksheets("Sheet1").Cells.Copy

' Open the destination workbook
Set destinationWorkbook = Workbooks.Open(Filename:="D:\Desktop\AUTHs.xlsm")
 
destinationWorkbook.Worksheets("Stop Work").Cells.PasteSpecial xlPasteAll

destinationWorkbook.Save

' Close the source workbook after saving changes
sourceWorkbook.Close SaveChanges:=False

 ActiveSheet.ListObjects(1).ListColumns(1).Range.End(xlDown).Select
    
     
End Sub

Solution

  • You need to check at the beginning of your code if any filters are present and if so remove them:

    Dim tbl As ListObject
    
    ' Open the source workbook
    Set sourceWorkbook = Workbooks.Open(Filename:="D:\Desktop\Stop Work.xlsm")
    
    ' Check if there are tables in the worksheet and clear filters if present
    Set ws = sourceWorkbook.Worksheets("Sheet1")
    On Error Resume Next
    For Each tbl In ws.ListObjects
        If tbl.AutoFilter Is Nothing = False Then
            tbl.AutoFilter.ShowAllData
        End If
    Next tbl
    On Error GoTo 0