macros在“主”选项卡中的列表中在Excel中创build新选项卡,并在每个选项卡中填充具有相同名称的单元格

我已经find了在“主”选项卡中创build和命名新选项卡的代码,但是我还需要在每个新选项卡的单元格中填充名称。 此外,我需要每个新的选项卡包含一个模板(不同于主选项卡),这只是一个空白表与标题和一些公式内置到一些列。 每个新选项卡都应该有完全相同的模板,但只有一个单元格(表格的标题)被填充以匹配选项卡的名称。

最后,我需要用户打开工作簿,填写主选项卡中的列表(不一定总是相同的长度,可能只是1),然后按下button(运行macros),并使选项卡根据上述创build。 看来,也许我需要创build一个隐藏的选项卡,其中包含要复制的模板? 这可能吗? 任何指导在这里将不胜感激。 谢谢!

假设您的母表被命名为“主”,模板被命名为“隐藏”。 您应该能够根据您的需要调整下面的代码。

(稍后提交我的答案,但我认为这将为您提供更多的灵活性,因为它是更清楚发生的事情)

Private Sub CommandButton1_Click() Dim masterSheet As Worksheet Dim hiddenSheet As Worksheet Dim NewSheet As Worksheet Dim myBook As Workbook Dim lastRow As Long Dim i As Long Dim namesColumn 'Define your workbook - here set as the active workbook, assuming it contains masterSheet and hiddenSheet Set myBook = ActiveWorkbook 'Define your worksheets - The sheets are named "Master" and "Hidden" respectively Set masterSheet = myBook.Worksheets("Master") Set hiddenSheet = myBook.Worksheets("Hidden") 'Define which column in your master tab the list is - here it's A ie column 1 namesColumn = 1 'Find the last row of the sheets list lastRow = masterSheet.Cells(masterSheet.Rows.Count, namesColumn).End(xlUp).Row 'Cycle through the list - Assuming the list starts in column "A" from the 2nd row For i = 2 To lastRow With myBook 'New sheet Set NewSheet = .Worksheets.Add(After:=.Worksheets("Master")) End With 'Find name of the tab and naming the tab tabName = masterSheet.Cells(i, namesColumn) NewSheet.Name = tabName 'Copy from hidden template - You can choose the ranges if predefined or use .Cells(r,c) to do something fancier hiddenSheet.Range("A1:F6").Copy _ Destination:=NewSheet.Range("A2:F7") 'Paste in eg cell A1 ie (1,1) the tab name NewSheet.Cells(1, 1).Value = tabName Next i End Sub 

欢迎来到StackOverflow。 这里有几点开始你的问题:

  1. 是的,这是可能的!
  2. Excel中没有选项卡,而是表格。
  3. 与表模板是一个好主意。 你可以把它放在一个隐藏的表格中,但记得为这个表单设置非常不寻常的名字,比如zZzmyVeryHiddenSheetzZz 。 这样,你可以确信没有人会尝试添加一个名字完全相同的工作表。
  4. 使用VBA,您可以将模板veryhidden ,即使从“取消隐藏表”菜单也无法访问。
  5. 使用macroslogging器! 开始录制macros,做你想做的,停止录制和检查你的代码。 您可以通过将光标放入您的macros代码并按F8来检查它是如何工作的。 代码所做的每个更改都会立即在工作簿中看到。
  6. 尝试在录制macros时使用键盘快捷键,例如用鼠标select范围,尝试使用shift+arrowctrl+shift+arrow组合。 这会产生更多的dynamic代码。

祝你好运!