简体   繁体   中英

Excel VBA - “Copy/Paste” pastes only value of selected range

I am writing a macro that opens a file selected by the user, copies all the data inside it and pastes it in another workbook already opened. The snippet of code looks like this :

Windows(fileToClose).Activate
ActiveSheet.Range("A1").EntireRow.Delete
ActiveSheet.Range("A1:G1", Selection.End(xlDown)).Select
Selection.Copy
ActiveWindow.Close SaveChanges:=False
Windows(fileKeepOpen).Activate
Sheets("DATA").Select
ActiveSheet.Range("B2:H2", Selection.End(xlDown)).Clear
ActiveSheet.Range("B2").Select
ActiveSheet.Paste

It works good execpt for the first column of the selection : it only takes the first value and pastes it everywhere in the destination column. For instance, if the first cell in the first column of the selection contains "A" and the second cell contains "B", the destination column will be filled with "A"s. But for the second column, no problem whatsoever.

PasteSpecial doesn't work at all also (each column has a different data format, and it looks like Excel doesn't want me to paste everything as values, since it keeps giving me a 1004 error).

Any ideas ?

I don't know what kind of data you have, but this should do the trick :

    Dim RS As String
RS = "A1:G" & Workbooks(fileToClose).ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row
'MsgBox RS


Workbooks(fileToClose).ActiveSheet.Range("A1").EntireRow.Delete
Workbooks(fileKeepOpen).Sheets("DATA").Range("B2:H2").End(xlDown).Clear


Workbooks(fileToClose).ActiveSheet.Range(RS).Copy Destination:=Workbooks(fileKeepOpen).Sheets("DATA").Cells(2, 2)

Workbooks(fileToClose).Close SaveChanges:=False

If it's not working let us know why! ;)

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