Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete worksheet in Excel using VBA

Tags:

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.

like image 854
Clauric Avatar asked Jul 17 '15 11:07

Clauric


People also ask

How do I Delete a worksheet in Excel VBA?

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”.

How do I Delete a worksheet in Excel VBA without warning?

To delete a worksheet without displaying a dialog box, set the Application. DisplayAlerts property to False.


2 Answers

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.

like image 139
Gary's Student Avatar answered Oct 16 '22 06:10

Gary's Student


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 
like image 36
R.Katnaan Avatar answered Oct 16 '22 08:10

R.Katnaan