I have a macros that generates a number of workbooks. I would like the macros, at the start of the run, to check if the file contains 2 spreadsheets, and delete them if they exist.
The code I tried was:
If Sheet.Name = "ID Sheet" Then Application.DisplayAlerts = False Sheet.Delete Application.DisplayAlerts = True End If If Sheet.Name = "Summary" Then Application.DisplayAlerts = False Sheet.Delete Application.DisplayAlerts = True End If
This code is returning an error:
run time error #424, object required.
I probably have the wrong formatting, but if there is an easier way to do this, it would be very useful.
To delete a sheet using VBA, you need to use the VBA Delete method. You need to specify the sheet that you want to delete and then use this method. Let's say if you want to delete the “Sheet1”, then you need to mention sheet1 and then type a dot (.) and in the end, type “Delete”.
To delete a worksheet without displaying a dialog box, set the Application. DisplayAlerts property to False.
Consider:
Sub SheetKiller() Dim s As Worksheet, t As String Dim i As Long, K As Long K = Sheets.Count For i = K To 1 Step -1 t = Sheets(i).Name If t = "ID Sheet" Or t = "Summary" Then Application.DisplayAlerts = False Sheets(i).Delete Application.DisplayAlerts = True End If Next i End Sub
NOTE:
Because we are deleting, we run the loop backwards.
Try this code:
For Each aSheet In Worksheets Select Case aSheet.Name Case "ID Sheet", "Summary" Application.DisplayAlerts = False aSheet.Delete Application.DisplayAlerts = True End Select Next aSheet
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With