Renaming Sheets with Vba

brettvba

MrExcel MVP
Joined
Feb 18, 2002
Messages
1,030
i have some code for renaming sheets which works fine until you try to do the same thing twice in a row for eg. Below


Sheets("111stk").Select
ActiveWindow.SelectedSheets.Delete
Sheets.Add
Sheets("Sheet1").Name = "111stk"
Sheets("211stk").Select
ActiveWindow.SelectedSheets.Delete
Sheets.Add
Sheets("Sheet2").Name = "211stk"
Range("G34").Select
Sheets("511stk").Select
ActiveWindow.SelectedSheets.Delete
Sheets.Add
Sheets("Sheet3").Name = "511stk"

has anyone got any better code so I don't have to refer to "Sheet3" and so on

HELp?
 

Excel Facts

Excel Joke
Why can't spreadsheets drive cars? They crash too often!
Hi BrettVBA

Looking @ your current code I would say that
you are currenly adding new sheets over the old ones
ie. deleting some currently setup sheets
then adding new ones Named as the same.
What you have found out is that the sheets
counter increments in the name. So that referencing the sheet as sheet3 etc is not valid after a 2nd call.
If your sheets names are cost as you have set up then
try this


<pre/>
Option Explicit
Option Base 1

Sub AddSheets()
Dim aSheets()
Dim i As Integer

aSheets = Array("111stk", "211stk", "511stk")

Application.DisplayAlerts = False
On Error GoTo ErrAdd
For i = 1 To 3
Sheets(aSheets(i)).Delete
Sheets.Add.Name() = aSheets(i)
Next

Exit Sub

ErrAdd:
MsgBox Err.Number & ":=" & Err.Description, vbSystemModal + vbMsgBoxHelpButton, _
"Error Adding Sheet", Err.HelpFile, Err.HelpContext

End Sub
</pre>
 
Upvote 0

Forum statistics

Threads
1,214,376
Messages
6,119,174
Members
448,870
Latest member
max_pedreira

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