简体   繁体   中英

Excel Vba copy and paste

While copying data from one Excel sheet to another workbook I have to paste data with the same format because each cell has interior color. I will also delete the data from the original sheet which I copied from. Is it possible to keep the source formatting?

Workbooks.Add
Set Outbook1 = ActiveWorkbook
OutBook.Activate
OutBook.Sheets("Sheet6").Select
Lines = ActiveSheet.Range("A65536").End(xlUp).Row
Range("A1:N" & Lines).Select
Selection.Copy

Outbook1.Activate
Outbook1.Sheets("Sheet1").Range("A1").PasteSpecial (xlPasteAll)

You can keep the source formatting (as long as it's not conditional formatting), using the PasteSpecial xlPasteAll command.

Recommendation : It's always better if you stay from Activate , Select and Selection , instead use referenced Workbook s and Sheets .

(for more details go to How to avoid using Select in Excel VBA macros )

Code

Option Explicit

Sub CopyBetweenSheets()

Dim Outbook1        As Workbook
Dim OutBook         As Workbook
Dim Lines           As Long

Set OutBook = ThisWorkbook
Set Outbook1 = Workbooks.Add

With OutBook
    With .Sheets("Sheet6")
        ' find last row in Column A in "Sheet6"
        Lines = .Cells(.Rows.Count, "A").End(xlUp).Row
        .Range("A1:N" & Lines).Copy
    End With
End With

' paste to "A1" in "Sheet1" in the new workbook
Outbook1.Sheets("Sheet1").Range("A1").PasteSpecial xlPasteAll

End Sub

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