I have a command button in a userform that runs this macro:
It worked fine at first, but after I close and reopen the Workbook excel throws "run-time error '9': Subscript out of range." If I click "Debug" then open the "Debug" dropdown in VBA and click the "Step into" command, excel throws another error: "Can't enter break mode at this time." If I click "Continue", excel runs all of the code correctly (including changing the codename) and the problem does not occur again until The Workbook is closed and reopened.
The error can also be corrected by making any change to the line of code where the error occurs (for instance, change "Sheets(NewLabelName)" to "ActiveSheet"). But the error consistently reoccurs the first time the code is called after opening the Workbook.
I really want the codename to be changed for each new Worksheet, but I can't have this error occuring every time my boss opens the Workbook. How can I solve this problem?
Rich (BB code):
Dim NewLabelName As String
'Create and name new sheet (including codename)
ActiveWorkbook.Sheets.Add 'creates new worksheet
ActiveSheet.Name = Product_Name_La.Caption 'Renames the Worksheet
ActiveSheet.Range("B2") = Product_Name_La.Caption 'Places the Worksheet name into a cell on the Worksheet
NewLabelName = ActiveSheet.Range("B2") 'Defines the variable "NewLabelName" (for later use)
ThisWorkbook.VBProject.VBComponents(Sheets(NewLabelName).CodeName).Name = "ProductLabel" _
& BD.Range("B2").Value 'Renames the Worksheet codename **this line is where the error occurs**
'BD.Range("B2").Value represents the amount of current worksheets plus 1
(A whole bunch of other code follows)
It worked fine at first, but after I close and reopen the Workbook excel throws "run-time error '9': Subscript out of range." If I click "Debug" then open the "Debug" dropdown in VBA and click the "Step into" command, excel throws another error: "Can't enter break mode at this time." If I click "Continue", excel runs all of the code correctly (including changing the codename) and the problem does not occur again until The Workbook is closed and reopened.
The error can also be corrected by making any change to the line of code where the error occurs (for instance, change "Sheets(NewLabelName)" to "ActiveSheet"). But the error consistently reoccurs the first time the code is called after opening the Workbook.
I really want the codename to be changed for each new Worksheet, but I can't have this error occuring every time my boss opens the Workbook. How can I solve this problem?