Last Row Paste to different Worksheet VBA

2019-09-16 05:16发布

I am trying to paste info on the last row of a different worksheet. I already have the info copied and this macro is just to paste it. With the code that I have now, I am getting an error that says "Paste Method of Worksheet Class Failed" how can I fix this?

here is the code:

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条回答
SAY GOODBYE
2楼-- · 2019-09-16 06:18

Excel is known to clear the clipboard and hence you should put the copy command one line before you paste.

So in your case the copy command will go before

ActiveSheet.Paste

Also please avoid the use of .Select/Activate. Please read How to avoid using Select in Excel VBA macros

Is this what you are trying (Untested)?

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
查看更多
登录 后发表回答