VBA:将数据从一个工作簿复制到另一个工作簿上的空行时出现错误1004

时间:2017-07-25 09:21:21

标签: excel vba excel-vba

尝试自动执行一些复制和粘贴工作,其中我有一个模板工作簿,当用户填写时,用户将运行一个宏,该宏将从现在填充的模板文档中复制并粘贴一行并将其粘贴到下一个空一排另一本工作簿。我运行它时仍然遇到错误,我不完全确定如何修改代码以使其工作

Sub hello()

ActiveSheet.Range(Cells(61, 1), Cells(61, 6)).Select   'selects the row of data from populated template
Selection.Copy                                          'copies that row
Workbooks.Open Filename:="destination workbook file path" 'opens destination workbook that needs the date pasted into
ActiveSheet.Range("A1").End(xlDown).Offset(1, 0).Select  'selects the next empty row in destination workbook
Selection.PasteSpecial xlPasteValues                    'pastes values not formulas
ActiveWorkbook.Save                                     'saves destination workbook

ActiveWorkbook.Close SaveChanges:=True                  'closes destination workbook

End Sub

当我运行它时,错误发生在它选择下一个空行的行上。

1 个答案:

答案 0 :(得分:0)

如果列中除了第1行以外的内容中没有任何内容,请不要使用End(xlDown)。请改为使用End(xlUp)

Sub hello()
    Dim srcRng As Range
    Dim dstWb As Workbook
    Dim dstRng As Range

    Set srcRng = ActiveSheet.Range(ActiveSheet.Cells(61, 1), ActiveSheet.Cells(61, 6))
    Set dstWb = Workbooks.Open(Filename:="destination workbook file path")
    With ActiveSheet  'Not a good idea - would be better to use With dstWb.Worksheets("specific_sheet_name")
        Set dstRng = .Cells(.Rows.Count, "A").End(xlUp).Offset(1, 0).Resize(1, 6)
        dstRng.Value = srcRng.Value
    End With
    dstWb.Save
    dstWb.Close SaveChanges:=False 'no need to save again as far as I can see    
End Sub