Excel VBA:根据单元格值插入N张表格

我是新的Excel VBA。 我想根据单元格值插入单元格的数量。

我有sheet1,我想使用b4作为参考张数(这是一个模板)插入。

例如,如果b4 = 4的值,我想复制模板4次。

我如何做到这一点在VBA?

谢谢。 🙂

没有魔法,一个一个地循环创造出来,把每一个新的结尾。 编辑:你也想要重命名他们1,2,3,4 …所以:

Sub CreateSheets() Dim i As Long With ThisWorkbook.Sheets For i = 1 To Sheet1.Range("B4").Value2 .Item("Template").Copy After:=.Item(.Count) .Item(.Count).Name = i Next End With End Sub 

或者像这样的东西…

 Sub CopyTemplate() Dim ws As Worksheet, wsTemplate As Worksheet Dim n As Integer, i As Long Application.ScreenUpdating = False Set ws = Sheets("Sheet1") Set wsTemplate = Sheets("Template") 'Where Template is the name of Template Sheet, change it as required. n = ws.Range("B4").Value If n > 0 Then For i = 1 To n wsTemplate.Copy after:=Sheets(Sheets.Count) ActiveSheet.Name = i Next i End If Application.ScreenUpdating = True End Sub 

像这样的东西应该工作:

 Sub copySheets() Dim i As integer Dim n As integer 'the amount of sheets n = Cells(4, 2).Value 'b4 For i = 2 To n If ActiveWorkbooks.Worksheets.Count < n Then 'Makes sure the sheets exists Dim ws As Worksheet Set ws = ThisWorkbook.Sheets.Add(After:= _ ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)) End If ws1.Copy ThisWorkbook.Sheets(Sheets.Count) 'copy data Next i End Sub