Changing sheet codename Run-Time Error 9: Subscript out of range

前端 未结 4 1139
死守一世寂寞
死守一世寂寞 2021-01-12 02:19

I\'ve code which, when I press a button, will add a new sheet to a workbook and change the codename of the sheet to make it easier to refer to later in my code.



        
4条回答
  •  既然无缘
    2021-01-12 02:46

    @Comintern already got you a working solution, but this code doesn't pollute your Immediate Window, and uses the hidden _CodeName property to change the sheet name instead of accessing the vbComponents collection.

    It also uses an early-bound Worksheet assignment to wks, and then a With block because it is accessing more than 1 member of wks.

    Interestingly, the placement of the VBProject member usage is important.

    Dim wbk As Workbook
    Dim wks As Worksheet
    
    Set wbk = ThisWorkbook
    Set wks = wbk.Worksheets.Add
    
    'Oddly, this statement MUST appear AFTER the Worksheets.add
    Debug.Assert wbk.VBProject.Name <> vbNullString 'Don't pollute the Immediate window
    
    With wks
      .Name = "Admin - Save Log"
      .[_CodeName] = "wksAdminSaveLog"
    End With
    

提交回复
热议问题