Delete Sheets if name not in approved list

TheRedCardinal

Board Regular
Joined
Jul 11, 2019
Messages
243
Office Version
  1. 365
  2. 2021
Platform
  1. Windows
Hi all,

My workbook has a setup sequence that reviews all of the sheets in the workbook, and the name doesn't match a list of sheets to keep, it deletes it.

I originally did this using an IF/AND statement that checked every single sheet name (early in my coding experience) but I need the user to be able to define the sheets themselves.

So I set up a range on a main data sheet, and called it "KeepSheets"

I then tried to adapt code I found on a similar question, and it looks as follows:

VBA Code:
For Counter = Sheets.Count To 1 Step -1

        WS2 = Application.Match(Sheets(Counter).Name, Range("KeepSheets"), 0)
        
        If IsError(WS2) Then
            WBk1.Sheets(Counter).Delete
        End If
    
    End If

Next Counter

I get "Object Variable or With Block variable not set" error on the Match section of the program.


WS2 is defined as a worksheet.

Can you see what I've done wrong?

Thanks!
 

Excel Facts

How to create a cell-sized chart?
Tiny charts, called Sparklines, were added to Excel 2010. Look for Sparklines on the Insert tab.
Change it to a Variant.

:rolleyes:

Thanks, Fluff, as ever!

I have a follow up question on this - I'll ask here but let me know if it needs a new thread.

My sheets are kept in a range - but this is awkward for the user because they would need to remember to redefine the named range each time they made an adjustment.

Better instead (and visually) would be to have a single cell, with the values stored separated by commas.

Could I do this?
 
Upvote 0
I would keep it as a range & use VBA to set the range, rather than using a named range.
 
Upvote 0

Forum statistics

Threads
1,214,561
Messages
6,120,242
Members
448,951
Latest member
jennlynn

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