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

前端 未结 4 1145
死守一世寂寞
死守一世寂寞 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:51

    If you need the VBE to have been opened, you can "trick" the debugging context into doing it for you. This seems to do whatever the project needs to update its indexing by forcing the VBE.MainWindow into existence:

    Dim wbk As Workbook
    Dim wks As Worksheet
    
    Set wbk = ThisWorkbook
    
    Set wks = wbk.Sheets.Add
    wks.Name = "Admin - Save Log"
    Debug.Print wbk.VBProject.VBE.MainWindow.Caption   '<--Force the VBE to exist.
    wbk.VBProject.VBComponents(wks.CodeName).Name = "wksAdminSaveLog"
    

    Edit:

    It seems that simply obtaining the reference to the VBE.MainWindow is enough (see the comments). This also works:

    Dim editor As Object
    Set editor = wbk.VBProject.VBE.MainWindow   '<--Force the VBE to exist.
    

提交回复
热议问题