简体   繁体   中英

VBA Copy Cells + Formatting without using the clipboard

I'm trying to copy cells from one sheet to another without copying stuff to the clipboard but it must copy the formatting across.

Here are the ways I've tried at the moment, any ideas how to accomplish my needs?

LastRow = ThisWorkbook.Sheets("Nas").Range("A65536").End(xlUp).Row

'Option 1, works but it's using the clipboard :/
ThisWorkbook.Sheets("Nas").Range("A" & 6 & ":F" & LastRow).Copy
ThisWorkbook.Sheets("Test").Range("A" & 6 & ":F" & LastRow).Offset(-5, 0).PasteSpecial

'Option 2, works but doesn't take formatting (ie text, general, time, date... etc)
Set Src = ThisWorkbook.Sheets("Nas").Range("A" & 6 & ":F" & LastRow)
Set Dst = ThisWorkbook.Sheets("Test").Range("A" & 6 & ":F" & LastRow).Offset(-5, 0).Resize(Src.Rows.Count, Src.Columns.Count)
Dst.Value = Src.Value

'Option 3, works but doesn't take formatting (ie text, general, time, date... etc)
ThisWorkbook.Sheets("Test").Range("A" & 6 & ":F" & LastRow).Offset(-5, 0) = ThisWorkbook.Sheets("Nas").Range("A" & 6 & ":F" & LastRow).Values

Your example code defines the formatting to be carried across as "text, general, time, date... etc" . While the number formatting (a subset of the Properties of a cell) can easily be accommodated, delving further into enumerating the vast number of properties and subproperties of a Cells object is counter-productive when all relevant ( non-default ) properties can be carried across easily with a copy/paste operation using the clipboard.

With ThisWorkbook.Sheets("Nas")
  LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
  ThisWorkbook.Sheets("Test").Range("A6:F" & LastRow).Offset(-5, 0) = _
    .Range("A6:F" & LastRow).Value
  ThisWorkbook.Sheets("Test").Range("A6:F" & LastRow).Offset(-5, 0).NumberFormat = _
    .Range("A6:F" & LastRow).NumberFormat
End With

Note that transferring the value of the cell across is performed with .Value or .Value2 not .Values .

I have seen this question popup occasionally and IMHO, the source of the question is likely a) a teacher that thinks this is a cutesy way to get students to appreciate just how many properties, subproperties and internal sub-subproperties a Range.Cells object ( Range Members (Excel) ) contains or b) some idiot with a fresh MBA that wants to prove they are smarter than the IT department. Enumerating through every possible formatting property a cell could contain is just a fool's errand (again IMHO) when the clipboard is available.

If you do attempt this yourself, don't forget Conditional Formatting and Comments, both of which can easily be attributed as part of a cell's formatting.

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