robjay
asked on
Excel VB: Creating a new page with a specific name
With VB in Excel, I'm attempting to create a new page with a specific name but it seems like the internal name given every time is Sheet1, Sheet2, etc. I also need some VB code to check for existence of this page and delete it.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
In my previous post, I illustrated how you can perform some different tasks:
1) Add a sheet with a given name
2) Delete a sheet
3) How to tell if a sheet exists
4) How to "AutoKill" a sheet if it exists (sub KillWorkSheet)
In the event you want to be able to add a sheet with a given name, and if a sheet by that name already exists to simply delete it and then add a new one with that name, you can use the following sub:
Public Sub AddSheet(ByVal SheetName As String)
On Error GoTo ErrHandler
ActiveWorkbook.Worksheets. Add().Name = SheetName
Exit Sub
ErrHandler:
Select Case Err.Number
Case 1004:
ActiveWorkbook.Worksheets( SheetName) .Delete
Resume
Case Else:
With Err
.Raise .Number, .Source, .Description, .HelpFile, .HelpContext
End With
End Select
End Sub
1) Add a sheet with a given name
2) Delete a sheet
3) How to tell if a sheet exists
4) How to "AutoKill" a sheet if it exists (sub KillWorkSheet)
In the event you want to be able to add a sheet with a given name, and if a sheet by that name already exists to simply delete it and then add a new one with that name, you can use the following sub:
Public Sub AddSheet(ByVal SheetName As String)
On Error GoTo ErrHandler
ActiveWorkbook.Worksheets.
Exit Sub
ErrHandler:
Select Case Err.Number
Case 1004:
ActiveWorkbook.Worksheets(
Resume
Case Else:
With Err
.Raise .Number, .Source, .Description, .HelpFile, .HelpContext
End With
End Select
End Sub
ASKER
Thanks! May have some follow up questions as I implement -
ASKER
Public Sub AddSheet(ByVal MySheet As String)
On Error GoTo ErrHandler
ActiveWorkbook.Worksheets. Add().Name = "MySheet"
Exit Sub
ErrHandler:
Select Case Err.Number
Case 1004:
ActiveWorkbook.Worksheets( MySheet).D elete
Resume
Case Else:
With Err
.Raise .Number, .Source, .Description, .HelpFile, .HelpContext
End With
End Select
End Sub
I get an error: subscript out of range when this is ran with MySheet in existance and highlight the Delete statement.
On Error GoTo ErrHandler
ActiveWorkbook.Worksheets.
Exit Sub
ErrHandler:
Select Case Err.Number
Case 1004:
ActiveWorkbook.Worksheets(
Resume
Case Else:
With Err
.Raise .Number, .Source, .Description, .HelpFile, .HelpContext
End With
End Select
End Sub
I get an error: subscript out of range when this is ran with MySheet in existance and highlight the Delete statement.
Dim wsh As Worksheet
For Each wsh In ActiveWorkbook.Sheets
If wsh.Name = SheetName Then
wsh.Delete
Exit For
End If
Next
Set wsh = ActiveWorkbook.Sheets.Add(
wsh.Name = SheetName
End Sub