Im trying to use the following code to copy sheets from my template file into and automatically generated worksheet.
Set wb = Workbooks("Generated.xlsx")
For Each sh In Workbooks("TemplateASA.xlsx").Worksheets
sh.Copy After:=wb.Sheets(wb.Sheets.Count)
Next sh
But I keep getting this error at compile: Run-time error '9' Subscript out of range
This will make it easier to find the problem - as above, I guess the workbook is not yet open. If I'm right, the Set wbTemplate = Workbooks("TemplateASA.xlsx")
line will fail. This isn't tested - let me know if it doesn't work.
Sub CopyWorksheets()
Dim wbGenerated as Workbook, wbTemplate as Workbook
Dim ws as Worksheet
Set wbGenerated = Workbooks("Generated.xlsx")
Set wbTemplate = Workbooks("TemplateASA.xlsx") 'If this line fails, remove it and uncomment the following line
' Set wbTemplate = Workbooks.Open("TemplateASA.xlsx", ,True) ' Opens as read only
For Each sh In wbTemplate.Worksheets
sh.Copy After:=wbGenerated.Sheets(wbGenerated.Sheets.Count)
Next sh
'wbTemplate.Close(False) 'Only required if you opened wbTemplate above
End sub
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.