Search code examples
vbaexcelexcel-2007

Add VBA code to dynamically created Excel sheets


I am working on an Excel workbook that has one initial sheet. This first sheet is a form that asks the users how many items in their project they have. The macro then generates a sheet for each item in their project.

Each generated sheet has buttons that perform specific functions, and these buttons have click events tied to them in the sheets code.

I have coded out all the functionality I need in the sheet in a static sheet.

I was wondering if there was a way to take this code and import it into all the dynamically created sheets once all the formatting and buttons are created by the form.

Any help would be greatly appreciated!


Solution

  • You could create a sheet named "Template" (potentially hidden) that would contain all the code and buttons and then use something like this:

    Sheets("Template").Copy After:=Sheets(Sheets.count)
    

    At this point, the Activesheet will be the newly copied sheet, so you can define a variable to refer to it and make all the changes you need. For example:

    Dim ws as Worksheet
    set ws = Activesheet
    ws.Range("A1") = "test"