最后一行粘贴到不同的工作表VBA

时间:2017-06-06 13:35:35

标签: vba excel-vba paste excel

我正在尝试将信息粘贴到不同工作表的最后一行。我已经复制了信息,这个宏只是为了粘贴它。使用我现在拥有的代码,我收到的错误是"工作表类的粘贴方法失败"我该如何解决这个问题?

这是代码:

Windows("m.xlsx").Activate
Cells(Application.Rows.Count, 1).End(xlUp).Offset(1, 0).Select
ActiveSheet.Paste
Range("D45").Select
Windows("d.xlsx").Activate

1 个答案:

答案 0 :(得分:0)

Excel已知清除剪贴板,因此您应该在粘贴之前将复制命令放在一行。

因此,在您的情况下,复制命令将在

之前
ActiveSheet.Paste

另请避免使用.Select/Activate。请阅读How to avoid using Select in Excel VBA macros

这是你正在尝试的(未经测试)?

Sub Sample()
    Dim thisWb As Workbook, thatWb As Workbook
    Dim lRow As Long

    Set thisWb = Workbooks("d.xlsx")
    Set thatWb = Workbooks("m.xlsx")

    '~~> Change Sheet1 to the relevant sheet
    With thatWb.Sheets("Sheet1")
        '~~> Find last Row to paste
        lRow = .Range("A" & .Rows.Count).End(xlUp).Row + 1

        '~~> Change Sheet1 to the relevant sheet
        '~~> Replace A1:A10 with the relevant range that you are trying to copy
        thisWb.Sheets("Sheet1").Range("A1:A10").Copy .Range("A" & lRow)
    End With
End Sub