简体   繁体   中英

Copying the data in Excel through VBA

As you can see down, I am copy 4 columns of data from one workbook to another. I am stuck at a case where the destination has 8 columns and my area of columns are 1,2,5,7. can you suggest me some changes in the code please. The one below will work only for first 4 columns. Thanks.

Sub Copymc()

Dim x As Workbook
Dim y As Workbook
Dim rng As Range

Set x = Workbooks.Open("H:\testing\Q4 2014\US RMBS Q4.xlsx")
Set y = Workbooks.Open("H:\testing\demo\test1.xlsx")

Dim LastRow As Long
Dim NextRow As Long

x.Worksheets("RL Holdings").Activate
Range("A65536").Select
ActiveCell.End(xlUp).Select
LastRow = ActiveCell.Row
Range("A2:D" & LastRow).Copy   

y.Worksheets("Sheet1").Range("a65536").End(xlUp).Offset(1, 0)
Application.CutCopyMode = False

End sub

The line Range("A2:D" & LastRow).Copy has column D hardcoded into it. This means that it will always copy A2 to D65536. If you want specific columns(A, B, E, G) then I would recommend simply repeating your code for each column.

For example

Range("A65536").Select
ActiveCell.End(xlUp).Select
Selection.Copy
y.Worksheets("Sheet1").Range("a65536").End(xlUp).Offset(1, 0).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False

then copy the code four times and replace the A to whatever column you want to copy or paste to. If this isn't what you are looking for please elaborate on what you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM