如何在Excel中的两个工作簿之间复制?

时间:2015-09-03 18:58:47

标签: excel vba excel-vba

我正在尝试在Excel中将一些信息从一个工作簿复制到另一个工作簿。我讨厌这种语言,我无法弄清楚何时使用激活等等......

这是我的代码,它给我一个运行时错误1004.我希望复制和粘贴工作,而不在工作表之间来回切换。我对代码的引用是here

这是我的实际代码:

Option Base 1

Sub populate_acc_template()
'
' populate_acc_template Macro
' Customer:  ACC.  This template populates the spreadsheet with data from an HRIS sheet.
'

' Start by defining the book to be pulled from and getting the first and last rows
' of that book.

    Dim template_book As Workbook
    Set template_book = ThisWorkbook
    Dim pull_book As Workbook
    Set pull_book = Workbooks.Open(Application.ActiveWorkbook.Path & "\books\sample_book.xlsx")

    With ActiveSheet
        FirstRow = 2
        LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
    End With

    insert_length = LastRow - FirstRow


' Now insert the number of rows that we need in the template.

    template_book.Sheets("Promotion Calculations").Rows(9 & ":" & 9 + insert_length).Insert Shift:=xlDown


' Copy and paste the information from the bulk data.

    Dim paste_array(1 To 9) As String

    paste_array(1) = 5
    paste_array(2) = 6
    paste_array(3) = 4
    paste_array(4) = 9
    paste_array(5) = 10
    paste_array(6) = 3
    paste_array(7) = 2
    paste_array(8) = 7
    paste_array(9) = 8

    For i = 1 To UBound(paste_array)

        ' Copy the entire column containing text.
         template_book.Sheets("Promotion Calculations").Range(Cells(8, paste_array(i)), Cells(8 + insert_length, paste_array(i))).Value = pull_book.Sheets("Data Sheet").Range(Cells(FirstRow, i), Cells(LastRow, i))
    Next i
End Sub

1 个答案:

答案 0 :(得分:0)

这个陈述存在一个问题(可能还有其他问题,但这显然是一个问题),因为看起来您在Cells分配中有Range无效。

template_book.Sheets("Promotion Calculations").Range(Cells(8, paste_array(i)), Cells(8 + insert_length, paste_array(i))).Value = pull_book.Sheets("Data Sheet").Range(Cells(FirstRow, i), Cells(LastRow, i))
Next i

如果不合格,Cells总是隐含地引用 ActiveSheet.Cells ,那么,问题在于您实际上是在做什么:

Sheet1.Range(Sheet1.Cells(1,1), Sheet1.Cells(1,2)).Value = Sheet2.Range(Sheet1.Cells(1,1), Sheet1.Cells(1,2)).Value

由于Sheet1上的Cells不能在Sheet2上产生Range,因此会产生1004错误。

如果您明确定义复制/粘贴的范围,我发现它通常更容易阅读/解释更清晰:

Dim pasteRange as Range
Dim copyRange as Range

For i = 1 To UBound(paste_array)
    With template_book.Sheets("Promotion Calculations")
        Set pasteRange = .Cells(8, paste_array(i)).Resize(insert_length, 1)
    End WIth

    With pull_book.Sheets("Data Sheet")
        Set copyRange = .Range(.Cells(FirstRow, i), .Cells(LastRow, i))
    End With

    pasteRange.Value = copyRange.Value

Next