简体   繁体   中英

VBA Excel: add sheet with template already in Workbook

Quick question:

I have a sheet TEMPLATE in my workbook. I want to add a number of similar sheet in that workbook, using TEMPLATE as a template.

How do I do this in VBA Excel?

For 5 additional TEMPLATES you need to copy it 5 times in the loop:

Dim i as byte
for i=1 to 5
    Sheets("TEMPLATE").Copy after:=sheets("TEMPLATE")
Next i

Here is an example that makes 13 copies:

Sub qwerty()
    For i = 1 To 13
        Sheets("TEMPLATE").Copy before:=Sheets(1)
    Next i
End Sub

modify this to suit your needs.

Just to register here in case anyone stumble on this answer as I did, you can also do it with a range if you don't want to copy the whole sheet, for example if your "Template" is just a range from another sheet

ThisWorkbook.Sheets("Master").Range("A2:L65536").Copy Destination:=ThisWorkbook.Sheets.Add(, Sheets("Data")).Range("A1")

What is important here:

Destination requires a range

Sheet.add returns a worksheet object.

so instead of passing sheetX.range as the Destination argument we are passing CreateNewSheetFunction.Range

Might not be a good example of code redability, but still, it's an option

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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