从整个外部工作表复制到主书中的工作表

时间:2018-12-13 17:36:16

标签: excel vba

此代码通过粘贴到工作表2中来完成-我可以切换到新的打开的工作簿,并看到它处于复制模式,但无法将其粘贴到Sheet2(Test)中。我已经尝试过“ Sheet2”和“ Test”,但是得到

  

运行时错误9:下标超出范围

请参见下面的片段

View

Sub ImportWorksheet999()

    Dim Wb1 As Workbook
    Dim MainBook As Workbook

    'Open All workbooks first:
    Set Wb1 = Workbooks.Open("G:\T\TWeir\Prod Ctrl\XML Reports\BDA\BDAREPORTtest.xlsx")
    Set MainBook = ActiveWorkbook

    'Now, copy what you want from wb1:
    Wb1.Sheets("BDA Report").Cells.Copy
    'Now, paste to Main worksheet:
    MainBook.Sheets("Sheet2").Range("A1").PasteSpecial

    'Close Wb's:
    Wb1.Close

End Sub

1 个答案:

答案 0 :(得分:1)

Set Wb1 = Workbooks.Open("G:\T\TWeir\Prod Ctrl\XML Reports\BDA\BDAREPORTtest.xlsx")
Set MainBook = ActiveWorkbook

打开文件会将其设置为ActiveWorkbook,因此您的Wb1MainBook都引用了打开的工作簿。

应该是

Set MainBook = ActiveWorkbook 'or ThisWorkbook if that's where the code is running
Set Wb1 = Workbooks.Open("G:\T\TWeir\Prod Ctrl\XML Reports\BDA\BDAREPORTtest.xlsx")