Last Row Paste to different Worksheet VBA

只谈情不闲聊 提交于 2020-01-17 04:44:08

问题


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:


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


来源:https://stackoverflow.com/questions/44391535/last-row-paste-to-different-worksheet-vba

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!