VBA Help - If worksheet(s) Exist then......

Johnny Thunder

Well-known Member
Joined
Apr 9, 2010
Messages
693
Office Version
  1. 2016
Platform
  1. MacOS
Hi guys, working on a code that will look into a newly opened workbook for either sheets ("R&O", "Executive Summary") if either or the sheets exists, delete them.

I came up with the below but do not know how to modify for multiple sheets and in the event one of the tabs don't exists look for the other.

Any help is appreciated!

Code:
Sub find ()

Dim ws             as worksheet
Dim Destbook    as workbook

Set DestBook = Workbooks.Open(vFilename) 'vfilename is defined on my full code

 For Each ws In DestBook.Worksheets 'Searches to ensure Sheets aren't already in workbook
         If ws.Name = "R&O" Then 
             Sheets("R&O").Delete
             End
    End If
        Next

End Sub
 

Excel Facts

Can you sort left to right?
To sort left-to-right, use the Sort dialog box. Click Options. Choose "Sort left to right"
Code:
         If ws.Name = "R&O" Then 
             Sheets("R&O").Delete

Change the above to
Code:
If ws.Name = "R&O" or ws.Name = [COLOR=#333333]"Executive Summary" then
ws.delete[/COLOR]
 
Upvote 0
As an alternative to Alan's solution, you could also do it without looping through all worksheets:

Code:
Application.DisplayAlerts = False
On Error Resume Next
With Destbook
    .Worksheets("R&O").Delete
    .Worksheets("Executive Summary").Delete
End With
On Error GoTo 0
Application.DisplayAlerts = True

Just FYI, if you google "worksheet exists site:mrexcel.com" you'll find many succinct variations on a function that will test whether a worksheet exists. These rely on referencing the worksheet and catching the error if it doesn't exist.
 
Upvote 0

Forum statistics

Threads
1,215,633
Messages
6,125,925
Members
449,274
Latest member
mrcsbenson

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top