VBA - copy and paste between sheets not pasting in the right location

大城市里の小女人 提交于 2020-06-17 09:32:22

问题


I am using VBA to paste some data from one sheet to another.

The first button press works as it is designed to (updating a row i45 etc).

The second button press was meant to paste data to the next row (i46 etc..) as it is empty row) but it actually updates the row i21 any subsequent presses just update i21 overwriting.

Can you please check what I have done wrong.

Private Sub CommandButton1_Click()
Application.ScreenUpdating = False
Dim copySheet As Worksheet
Dim pasteSheet As Worksheet

Set copySheet = Worksheets("Raw")
Set pasteSheet = Worksheets("Week Data (all)")

copySheet.Range("H15:AA15").Copy
pasteSheet.Cells(45, 9).End(xlUp).Offset(1, 0).PasteSpecial xlPasteValues
Application.CutCopyMode = False
Application.ScreenUpdating = True
End Sub

回答1:


That's because with pasteSheet.Cells(45, 9) you are always starting your search at Row 45. Instead, you should start your search at .Rows.Count, which is the absolutely last row in your column (ie. 1048576). Therefore, try...

With pasteSheet
    .Cells(.Rows.Count, 9).End(xlUp).Offset(1, 0).PasteSpecial xlPasteValues
End With



回答2:


also this mothod same.

Private Sub CommandButton1_Click()
Dim vDB
Dim rngT As Range
Dim copySheet As Worksheet
Dim pasteSheet As Worksheet

    Application.ScreenUpdating = False

    Set copySheet = Worksheets("Raw")
    Set pasteSheet = Worksheets("Week Data (all)")

    vDB = copySheet.Range("H15:AA15")

    Set rngT = pasteSheet.Cells(Rows.Count, 9).End(xlUp)(2)
    rngT.Resize(UBound(vDB, 1), UBound(vDB, 2)) = vDB

    Application.ScreenUpdating = True
End Sub


来源:https://stackoverflow.com/questions/44780246/vba-copy-and-paste-between-sheets-not-pasting-in-the-right-location

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