Connecting Tech Pros Worldwide Help | Site Map

Getting Run-time error '9': when trying to open workbook and delete all sheets but 1

Newbie
 
Join Date: Aug 2009
Posts: 1
#1: Aug 12 '09
I'm trying to delete sheets 1,2,4,5 and make sheet 3 the active one. I get the error on " Sheets(1).Select" and "Sheets(Array(1, 2, 4, 5)).Select". I get a run time error when I try and run the following macro. Help?


zFolder = zPath & "\Kitty*"
Application.DisplayAlerts = False
Sheets(1).Select
ActiveWindow.ScrollWorkbookTabs Position:=xlFirst
ActiveWindow.ScrollWorkbookTabs Position:=xlFirst
Sheets(Array(1, 2, 4, 5)).Select
Sheets(1).Activate
ActiveWindow.SelectedSheets.Delete
On Error Resume Next
Sheets("regress").Delete
On Error GoTo 0
Application.DisplayAlerts = True
Expert
 
Join Date: Jun 2007
Location: Derbyshire, UK
Posts: 346
#2: Aug 17 '09

re: Getting Run-time error '9': when trying to open workbook and delete all sheets but 1


Quote:

Originally Posted by grippy10 View Post

I'm trying to delete sheets 1,2,4,5 and make sheet 3 the active one. I get the error on " Sheets(1).Select" and "Sheets(Array(1, 2, 4, 5)).Select". I get a run time error when I try and run the following macro. Help?


zFolder = zPath & "\Kitty*"
Application.DisplayAlerts = False
Sheets(1).Select
ActiveWindow.ScrollWorkbookTabs Position:=xlFirst
ActiveWindow.ScrollWorkbookTabs Position:=xlFirst
Sheets(Array(1, 2, 4, 5)).Select
Sheets(1).Activate
ActiveWindow.SelectedSheets.Delete
On Error Resume Next
Sheets("regress").Delete
On Error GoTo 0
Application.DisplayAlerts = True

Hi

I have more questions than answers, but this will do what you have described.
Expand|Select|Wrap|Line Numbers
  1. Sub DeleteActiveBookSheetsExceptSheet3()
  2.     Dim i As Integer
  3.     Application.DisplayAlerts = False
  4.         With ActiveWorkbook
  5.             For i = .Sheets.Count To 1 Step -1
  6.                 If i <> 3 And .Sheets.Count > 1 Then .Sheets(i).Delete
  7.             Next i
  8.         End With
  9.     Application.DisplayAlerts = True
  10. End Sub
With some mods you can probably bend it to suit your requirements!!


MTB
Reply