Case not recognized in Select Case

K

kevlarmcc

I am using Select Case in a macro that deletes worksheets to skip
specifically named worksheets. Code is:

For Each Worksheet In Worksheets
Select Case Worksheet.name
Case "Sheet1", 'Sheet2", "Sheet3", etc.

Case Else

Worksheet.Activate
Application.DisplayAlerts = False
ActiveSheet.Delete
Application.DisplayAlerts = True


End Select
Next Worksheet

The problem is I have a worksheet named "BGE" that I want skipped and the
select case is not recognizing it and deletes it. I wonder if this has to do
with Excel 2k7 using BGE as a cell value. Any ideas?
 
R

Ron Rosenfeld

I am using Select Case in a macro that deletes worksheets to skip
specifically named worksheets. Code is:

For Each Worksheet In Worksheets
Select Case Worksheet.name
Case "Sheet1", 'Sheet2", "Sheet3", etc.

Case Else

Worksheet.Activate
Application.DisplayAlerts = False
ActiveSheet.Delete
Application.DisplayAlerts = True


End Select
Next Worksheet

The problem is I have a worksheet named "BGE" that I want skipped and the
select case is not recognizing it and deletes it. I wonder if this has to do
with Excel 2k7 using BGE as a cell value. Any ideas?

BGE is not in your Case statement; so when Worksheet.Name = BGE, the case else
code will get executed, and the sheet will be deleted.
--ron
 
C

Chip Pearson

You are using ActiveSheet.Delete which will always delete that sheet
that is active in Excel. It is NOT the sheet that is iterated by the
For Each loop. You need to either select that sheet,
(Worksheet.Select) or use the For Each variable (Worksheet.Delete). It
is a common misconception that a For Each loop activates the
ActiveSheet or ActiveCell. Such is not the case. If you expect a sheet
or cell to be active, you must activate it yourself.

Cordially,
Chip Pearson
Microsoft Most Valuable Professional,
Excel, 1998 - 2010
Pearson Software Consulting, LLC
www.cpearson.com
 
W

Wouter HM

Hi Chip,

I think you are looking for something like:

Sub DeleteSheets()
Dim sht As Worksheet

For Each sht In ActiveWorkbook.Sheets
Select Case sht.Name
Case "Sheet1", "Sheet2", "BGE"
' Complete list of sheets to preserve
Case Else
Application.DisplayAlerts = False
sht.Delete
Application.DisplayAlerts = True
End Select
Next
End Sub


HTH,

Wouter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top