7

For some reason the below code only works when run in the vbe, when run in the event handling code, or by macro list the codename remains sheet1.

Please can someone investigate ?

Sub changesheetcodename()    

Dim ws,tsst as worksheet

For Each Ws In ActiveWorkbook.Worksheets
    If Ws.Name <> "Instructions"  then ws.delete
Next Ws

Worksheets.Add(After:=Worksheets(Worksheets.Count)).Name = "Sheet1"

set tsst = Sheets("Sheet1")
With tsst
    .Parent.VBProject.VBComponents(.CodeName) _
    .Properties("_CodeName") = "test"
End With

End Sub
7
  • Could you add a variable type into your example? Dim tsst As ...
    – miroxlav
    Jul 17, 2015 at 9:51
  • Please provide your full code block. It is difficult to work out your issue without it. I can't see the class type assigned to tsst which is important. As it stands, it should error because as far as I can see, tsst is set to Nothing.
    – joehanna
    Jul 17, 2015 at 9:52
  • Are you trying to change the code name of the sheet where the code is running? Where is your code actually located? Jul 17, 2015 at 10:13
  • Hi I didn't want to provide all the code as I felt it might confuse things however, I have now amended my code. The code is located in "This workbook", I have also tried running it in a separate module and the results are the same
    – Krishn
    Jul 17, 2015 at 10:43
  • Just to mention, ws is currently being declared as a Variant. You cannot declare multiple variables in this format with VBA. You would rather need to Dim ws as Worksheet, tsst as Worksheet for both to be declared as worksheets.
    – luke_t
    Jul 17, 2015 at 10:47

1 Answer 1

8
Sub change_code_name()
  Dim wbk As Object, sheet As Object
  ActiveWorkbook.VBProject.Name = "VBAProject"
  Set wbk = ActiveWorkbook.VBProject.VBComponents(ActiveWorkbook.CodeName)
  wbk.Name = "wbk_code_name"
  Set sheet = ActiveWorkbook.VBProject.VBComponents(ActiveWorkbook.Sheets(1).CodeName)
  sheet.Name = "sheet_code_name"
End Sub

Also the access to the VBAProject is required: see "Macro settings" and set "Trust access to the VBA object model". To programmatically change the settings, look here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.