我尝试使用以下代码将工作表从我的模板文件复制到并自动生成工作表。
Set wb = Workbooks("Generated.xlsx")
For Each sh In Workbooks("TemplateASA.xlsx").Worksheets
sh.Copy After:=wb.Sheets(wb.Sheets.Count)
Next sh
但我在编译时不断收到此错误:运行时错误'9'下标超出范围
这将更容易找到问题 - 如上所述,我猜工作簿尚未打开。如果我是对的,这Set wbTemplate = Workbooks("TemplateASA.xlsx")
条线就会失败。这未经测试 - 如果它不起作用,请告诉我。
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