如何使用VBA将工作表从一个工作簿复制到另一个工作簿?

时间:2013-01-21 12:52:50

标签: excel-vba vba excel

我尝试使用以下代码将我的模板文件中的工作表复制到自动生成的工作表中。

 Set wb = Workbooks("Generated.xlsx")
For Each sh In Workbooks("TemplateASA.xlsx").Worksheets
   sh.Copy After:=wb.Sheets(wb.Sheets.Count)
Next sh

但是我在编译时遇到了这个错误: 运行时错误'9' 下标超出范围

1 个答案:

答案 0 :(得分:0)

这样可以更容易地找到问题 - 如上所述,我想工作簿尚未打开。如果我是对的,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