Dear Excel, VBA community!
I have an issue with my VBA code and hoping someone could very kindly assist!
The code below is meant to delete multiple records across all excel sheets based on two or more criteria. So far I have made it for just two criteria where the user inputs the product type and date.
However, the VBA code fails for the section which is highlighted below. Any advice and help would be great, thank you all very much!
Best,
Manerlao
Section which has the error:
Full code:
I have an issue with my VBA code and hoping someone could very kindly assist!
The code below is meant to delete multiple records across all excel sheets based on two or more criteria. So far I have made it for just two criteria where the user inputs the product type and date.
However, the VBA code fails for the section which is highlighted below. Any advice and help would be great, thank you all very much!
Best,
Manerlao
Section which has the error:
VBA Code:
'1. Apply Filter
For Each ws In ActiveWorkbook.Sheets
ws.Range("A2:XX1000000").AutoFilter Field:=1, Criteria1:=tCriteria
ws.Range("A2:XX1000000").AutoFilter Field:=3, Criteria1:=sCriteria
Full code:
VBA Code:
Sub DeleteSelectedRws()
'Delete records based on date and product
'Display Yes/No message prompt before deleting rows
Dim ws As Worksheet
Dim lRows As Long
Dim vbAnswer As VbMsgBoxResult
Dim sCriteria As Variant
Dim tCriteria As Variant
'Set reference to the sheet and Table.
Set ws = ActiveSheet
ws.Activate 'Activate sheet that Table is on.
'Clear any existing filters
'Ask user for input
sCriteria = Application.InputBox(Prompt:="Please enter the filter criteria for the PRODUCT column." _
& vbNewLine & "Leave the box empty to filter for blanks.", _
Title:="Filter PRODUCT (1 of 2)", _
Type:=2)
tCriteria = Application.InputBox(Prompt:="Please enter the filter criteria for the DATE column." _
& vbNewLine & "Leave the box empty to filter for blanks.", _
Title:="Filter DATE (2 of 2)", _
Type:=2)
'Exit if user presses Cancel button
If sCriteria = False And tCriteria = False Then Exit Sub
'1. Apply Filter
For Each ws In ActiveWorkbook.Sheets
ws.Range("A2:XX1000000").AutoFilter Field:=1, Criteria1:=tCriteria
ws.Range("A2:XX1000000").AutoFilter Field:=3, Criteria1:=sCriteria
'Count Rows & display message
On Error Resume Next
lRows = WorksheetFunction.Subtotal(103, ws.Range("A2:A1000000").SpecialCells(xlCellTypeVisible))
On Error GoTo 0
Next ws
vbAnswer = MsgBox(lRows & " Rows will be deleted. Do you want to continue?", vbYesNo, "Delete Rows Macro")
If vbAnswer = vbYes Then
'Delete Rows
Application.DisplayAlerts = False
ws.Range("A2:XX1000000").SpecialCells(xlCellTypeVisible).Delete
Application.DisplayAlerts = True
'Clear Filter
For Each ws In ActiveWorkbook.Sheets
ws.Activate
ws.ShowAllData
ws.Range("A1").Select
Next ws
Else
For Each ws In ActiveWorkbook.Sheets
ws.Activate
ws.ShowAllData
ws.Range("A1").Select
Next ws
End If
End Sub