Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

excel

vba

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 to this spreadsheet. Is there anyway I can do this?

like image 471
Hannah Avatar asked Dec 27 '22 18:12

Hannah


1 Answers

Jook has already explained how it works. I will take it a step further.

The syntax of adding a worksheet is

expression.Add(Before, After, Count, Type)

If you check inbuilt Excel's help then you can see what Before, After, Count, Type stands for

FROM EXCEL"S HELP

Parameters (All 4 parameters are Optional)

  1. Before - An object that specifies the sheet before which the new sheet is added.
  2. After - An object that specifies the sheet after which the new sheet is added.
  3. Count - The number of sheets to be added. The default value is one.
  4. Type - Specifies the sheet type. Can be one of the following XlSheetType constants: xlWorksheet, xlChart, xlExcel4MacroSheet, or xlExcel4IntlMacroSheet. If you are inserting a sheet based on an existing template, specify the path to the template. The default value is xlWorksheet.

Once the sheet is created then you need to use .insertlines to create the relevant procedure and to also embed the code that you want to run.

NOTE - IMP: If you want the code to embed code in the VBA project, you need to ensure that you have "Trust Access to the VBA Project Object Model" selected. See snapshot.

enter image description here

Here is an example where I am creating a sheet and then embedding a Worksheet_SelectionChange Code which will display a message "Hello World"

CODE - TRIED AND TESTED

Option Explicit

Sub Sample()
    Dim ws As Worksheet
    Dim nLines As Long
    Dim VBP As Object, VBC As Object, CM As Object
    Dim strProcName As String

    Set ws = Worksheets.Add

    Set VBP = ThisWorkbook.VBProject
    Set VBC = VBP.VBComponents(ws.Name)
    Set CM = VBC.CodeModule

    strProcName = "Worksheet_SelectionChange"

    With ThisWorkbook.VBProject.VBComponents( _
    ThisWorkbook.Worksheets(ws.Name).CodeName).CodeModule
        .InsertLines Line:=.CreateEventProc("SelectionChange", "Worksheet") + 1, _
        String:=vbCrLf & _
        "    Msgbox ""Hello World!"""
    End With
End Sub

This is how the new sheet code area looks once you run the above code.

enter image description here

like image 188
Siddharth Rout Avatar answered Dec 30 '22 12:12

Siddharth Rout