How to specify start row for a “copy column vba”?

主宰稳场 提交于 2019-12-11 21:08:05

问题


I'm using the following string to copy a column from one sheet to another

Dim wsCore As Worksheet
Dim wsData As Worksheet

Set wsCore = Sheets("R2 Data Dump")
Set wsData = Sheets("Active")

Dim rowNumber As Integer
Dim cellFormulas As Variant
Dim cellFormulas1 As Variant
Dim counter As Integer
    counter = 0
Dim currentCell As String
Dim importSheetCell As Variant
Dim importSheetOffset As Variant
Dim contractnum As Integer
Dim pt As PivotTable
Dim ws As Worksheet
Dim pc As PivotCache
Dim lastrow As Long

Set wsCore = Sheets("R2 Data Dump")
Set wsData = Sheets("Active")

    Sheets("R2 Data Dump").Visible = True
    Sheets("R2 Data Dump").Select
    rowNumber = ActiveSheet.UsedRange.Rows.Count

 With wsCore
 Startrow = 3

    wsCore.Columns("W").Copy Destination:=wsData.Columns("A")
    wsCore.Columns("B").Copy Destination:=wsData.Columns("B")
    wsCore.Columns("C").Copy Destination:=wsData.Columns("C")
    wsCore.Columns("D").Copy Destination:=wsData.Columns("D")

End With.

So what is does is copy the particular columns from one sheet and paste it on the specified column of the destination sheet. My problem is, the action starts pasting the copied cell from the source sheet to the first row on the destination cell. What I would like to find out is how can I set a row number where it would start pasting instead of row 1.


回答1:


Typically, you would go to the first blank cell in the column (looking from the bottom up).

With Intersect(wsCore.Columns("A:W"), wsCore.UsedRange)
    .Columns("W").Copy Destination:=wsData.Cells(Rows.Count, "A").End(xlUp).Offset(1, 0)
    .Columns("B").Copy Destination:=wsData.Cells(Rows.Count, "B").End(xlUp).Offset(1, 0)
    .Columns("C").Copy Destination:=wsData.Cells(Rows.Count, "C").End(xlUp).Offset(1, 0)
    .Columns("D").Copy Destination:=wsData.Cells(Rows.Count, "D").End(xlUp).Offset(1, 0)
End With

If you wanted to specify a row, declare a long variable and use that.

Dim rw As Long
rw = 10
With Intersect(wsCore.Columns("A:W"), wsCore.UsedRange)
    .Columns("W").Copy Destination:=wsData.Cells(rw, "A")
    .Columns("B").Copy Destination:=wsData.Cells(rw, "B")
    .Columns("C").Copy Destination:=wsData.Cells(rw, "C")
    .Columns("D").Copy Destination:=wsData.Cells(rw, "D")
End With

I've used Intersect to guard against trying to copy a full column into a column that doesn't start at the first row. A full column won't fit.



来源:https://stackoverflow.com/questions/29359107/how-to-specify-start-row-for-a-copy-column-vba

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