Login or Sign up Help | Site Map
Connecting Tech Pros Worldwide

Select & Delete Sheets in Workbook using Wildcard

Question posted by: deve8ore (Newbie) on July 2nd, 2008 06:54 PM
Hello,

I have an Excel workbook with ~ 21 sheets in it.
Let's say 7 are named "Red1", "Red2", "Red3", ect....
Another 7 are named for "Green1, 2, 3", ect...
and the last 7 are named "Blue1, 2, 3", ect...

I'm trying to write a very basic code to go though the entire Workbook, select and then delete all sheets with the name containing "Red*" (regardless of the following number). So far I have:

Sub DeleteRed()
Dim ws As Worksheet
Dim x As Integer
x = 1
For Each ws In ActiveWorkbook.Sheets
x = x + 1
For Each ws In ActiveWorkbook.Sheets
If Left(ws.Name, 3) = "Red" Then
ActiveSheet.Delete
End If
Next ws
End Sub

Yes I am a novice, and any help would be appreciated!

Thank you.
Would you like to answer this question?
Sign up for a free account, or Login (if you're already a member).
MikeTheBike's Avatar
MikeTheBike
Expert
256 Posts
July 4th, 2008
11:52 AM
#2

Re: Select & Delete Sheets in Workbook using Wildcard
Hi

On the basis that the 'Colour' (or any other string) is always at the begining of the sheet name, then this will delete any name series you care to create.

Note: this will delete sheets without notification. If that is a problem just delete the line
Application.DisplayAlerts = False
from the code

Also it will not delete the last sheet (it will throw an error if you try and delete every sheet).

The UCase() functions make this not case sensitive, again remove these if you want case sensitivity.

Code: ( text )
  1. Sub DeleteSheetColour(ByVal strColour As String)
  2.     Dim ws As Worksheet
  3.     Dim NLen As Integer
  4.    
  5.     NLen = Len(strColour)
  6.     For Each ws In ActiveWorkbook.Sheets
  7.         With ws
  8.             If Left(UCase(.Name), NLen) = UCase(strColour) Then
  9.                 If ThisWorkbook.Sheets.Count > 1 Then
  10.                     Application.DisplayAlerts = False
  11.                     .Delete
  12.                     Application.DisplayAlerts = True
  13.                 End If
  14.             End If
  15.         End With
  16.     Next ws
  17. End Sub
  18.  
  19. Sub TestSheetDelete()
  20.     DeleteSheetColour "Green"
  21. End Sub

HTH

MTB

Last edited by MikeTheBike : July 4th, 2008 at 11:54 AM. Reason: More info
Reply
deve8ore's Avatar
deve8ore
Newbie
27 Posts
July 12th, 2008
01:04 AM
#3

Re: Select & Delete Sheets in Workbook using Wildcard
Thanks.... I appreciate your help!!

Reply
Reply
Not the answer you were looking for? Post your question . . .
180,431 Experts ready to help you find a solution.
Sign up for a free account, or Login (if you're already a member).

Top Visual Basic Forum Contributors