How to add a new spreadsheet with VBA-Code, using VBA

后端 未结 3 1695
情歌与酒
情歌与酒 2021-01-03 01:36

I am creating a macro and part of the macros function is to make VBA create a new spreadsheet. Because of the nature of distribution the name will change. I need to add code

3条回答
  •  北海茫月
    2021-01-03 02:09

    the following code will add you a spreadsheet.

    Public Sub Workbook_Add()
     Dim wks As Worksheet
     Set wks = ThisWorkbook.Worksheets.Add(, , 1, xlWorksheet)
     With wks
       'set codename of wks
       ThisWorkbook.VBProject.VBComponents(.CodeName).Name = "tblWhatever"
       'set tablename of wks
       .Name = "whatever"
       'add code (untested demo)
       'ThisWorkbook.VBProject.VBComponents(.CodeName).CodeModule.InsertLines 1, "Option Explicit"
       'add code (as of example from excel-help)
       'Application.VBE.CodePanes(1).CodeModule.InsertLines 1, "Option Explicit"
     End With
    End Sub
    

    If you need to add VBA-Code to this specific spreadsheet, you should further inspect the VBProject object - look for CodeModule and then i.e. InsertLines.

    A further hint for you - I would try to use the CodeNames of your tables. It is less likely to be changed - BUT it might be not that comfortable to use in your code at first. I had to get used to it, but for me it has many advantages against using a tables name.

    Hope this helps ;)

提交回复
热议问题