简体   繁体   English

将VBA代码添加到动态创建的Excel工作表

[英]Add VBA code to dynamically created Excel sheets

I am working on an Excel workbook that has one initial sheet. 我正在处理一张有一张初始工作表的Excel工作簿。 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! 任何帮助将不胜感激!

You could create a sheet named "Template" (potentially hidden) that would contain all the code and buttons and then use something like this: 您可以创建一个名为“ Template”(可能已隐藏)的工作表,其中包含所有代码和按钮,然后使用如下代码:

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. 此时,Activesheet将是新复制的工作表,因此您可以定义一个变量来引用它并进行所需的所有更改。 For example: 例如:

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

As @cyboashu said, just copy the sheet and it will copy all formulas and formatting over. 正如@cyboashu所说,只需复制工作表,它将复制所有公式并格式化。 At that point, any additional changes that are needed can still be made to the individual sheets. 那时,仍然可以对单个工作表进行任何其他更改。 They are not linked copies. 它们不是链接副本。

Here's a quick and dirty macro to copy worksheet(1) to the end of the workbook and rename. 这是一个快速而肮脏的宏,用于将工作表(1)复制到工作簿的末尾并重命名。 If you need to do any formatting, you can do it immediately after the paste using ActiveSheet. 如果需要进行任何格式化,则可以在使用ActiveSheet粘贴后立即进行格式化。 Assigning your new Activesheet to a variable to reference later is better practice but I'm not 100% sure how to do that without digging in further. 将新的Activesheet分配给变量以供以后引用是一种较好的做法,但是我不确定100%如何做到这一点而无需进一步研究。 Maybe someone can elaborate. 也许有人可以详细说明。

    Sub copysheet()
    Dim Mainws As Worksheet
    Dim Mainwb As Workbook
    Set Mainwb = ThisWorkbook
    Set Mainws = ThisWorkbook.Worksheets(1)

    i = Mainwb.Worksheets.Count

    With Mainwb
       Mainws.Copy after:=Worksheets(i)
       Worksheets(i + 1).Name = "Copied Worksheet"
    End With
    With ActiveSheet
        Cells(1, 1).Value = "Copied Sheet"
        'other formatting changes
    End With

    'increment i variable if you plan to make more copies in a loop
    'i = Mainwb.Worksheets.Count

    End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM