Why does this code fail?

AC

Board Regular
Joined
Mar 21, 2002
Messages
153
This works using excel 2003
Code:
Sub ChangeVBACodeName()
'will change the active sheets code name to MySheet25
Dim SN As String
SN = ActiveSheet.Name
ThisWorkbook.VBProject.VBComponents(SN).Name = "MySheet25"
End Sub

But this does not, Why
Code:
Sub test()
Dim SN As String
Sheets.Add.Move after:=Sheets(1)
ActiveSheet.Name = "Sheet22"
SN = ActiveSheet.Name
ThisWorkbook.VBProject.VBComponents(SN).Name = "MySheet25"
End Sub
 

Excel Facts

Select all contiguous cells
Pressing Ctrl+* (asterisk) will select the "current region" - all contiguous cells in all directions.
Have you trusted access to the VB Project?

Home button > Excel Options > Trust Center > Macro Settings

Denis
 
Upvote 0
In your 1st code, the Sheet name and its' VBComponent name are the same name e.g. "Sheet1". So when you want to change the VBComponent name of Sheet1, this works...
ThisWorkbook.VBProject.VBComponents(Sheet1).Name = "MySheet25"

In your 2nd code (test), you create a new worksheet and rename it "Sheet22". It's VBComponent is not named Sheet22. It's VBComponent name is something like Sheet4 or Sheet5, or however many sheets you have already created (including the deleted ones). So there is no VBComponent named "Sheet22" and this fails...
ThisWorkbook.VBProject.VBComponents(Sheet22).Name = "MySheet25"

Try this instead assuming you don't already have a MySheet25 VBComponent.
SN = ActiveSheet.CodeName
ThisWorkbook.VBProject.VBComponents(SN).Name = "MySheet25"
 
Last edited:
Upvote 0

Forum statistics

Threads
1,224,522
Messages
6,179,297
Members
452,903
Latest member
Knuddeluff

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