VBA to delete sheets loop

shabangle

New Member
Joined
Aug 9, 2013
Messages
23
Hi All,

I need a script that will delete sheets based on an earlier calculation. TabDiff2 is defined earlier.

I have the following code which is breaking:

For v = TabDiff2 To 1 Step -1
Sheets("2_Weightings").Index -v.Select
Application.DisplayAlerts = False
ActiveWindow.SelectedSheets.Delete
Application.DisplayAlerts = True
Next v

Is there a problem with selecting sheets using their index dynamically?

How else could I do this?

Thanksfor any help,
Shabangle
 

Excel Facts

Wildcard in VLOOKUP
Use =VLOOKUP("Apple*" to find apple, Apple, or applesauce
If you wanted to select a sheet by index based on the index of the sheet '2_Weightings' and the value of v you would need something like this.
Code:
Sheets(Sheets("2_Weightings").Index-v).Select

PS You don't need to select a sheet to delete it.
Code:
Application.DisplayAlerts = False
Sheets(Sheets("2_Weightings").Index-v).Delete
Application.DisplayAlerts = True
 
Upvote 0
The index just returns an integer so in essence you are trying to select the integer which isn't an object.

This is untested so try on a copy...

Code:
Sheets(Sheets("2_Weightings").Index - v).Select

Also Selecting isn't usually he best way..

Code:
    For v = TabDiff2 To 1 Step -1
        Application.DisplayAlerts = False
        Sheets(Sheets("2_Weightings").Index - v).Delete
        Application.DisplayAlerts = True
    Next v
 
Upvote 0
Thanks muchly for both replies.

Out of curiosity what is the application display alerts toggle doing? Would an alert be triggered by this operation?
 
Upvote 0
When you delete a sheet Excel will pop up a confirmation dialog, turning DisplayAlerts off prevents that happening.
 
Upvote 0

Forum statistics

Threads
1,223,907
Messages
6,175,300
Members
452,633
Latest member
DougMo

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