简体   繁体   中英

Excel vba : assign all properties to a cell from an array of range

My goal is to save a Cell and all its properties and value in an array of range, and then write back all properties and values of this cell to another cell from the array (like a copy paste function but pasting from the array).

Here is a simple test procedure :

Sub Test()
    Dim Range_Grid(1) As Range
    Dim CellAdress As String
    Dim i As Long

    Set Range_Grid(1) = ActiveSheet.Cells(2, 3)
    ActiveSheet.Cells(4, 1) = Range_Grid(1)
End Sub

So here in the first element of the array Range_Grid(1), I really get the full range saved and I can access every property the original range ActiveSheet.Cells(2, 3) had, like font style, format, color, comment, etc..

But when I try to write this range from array to another empty cell, it only write the value...

Any idea how to write all the properties from the array like if it was a copy/paste from sheet to sheet?

There is no way of moving all of the formatting from a range in an array back into excel at once. This leaves you with two options: either you copy within excel as Scott Craner suggested, or you copy each type of formatting individually. For example, if you wanted to copy the value (which is the default and hence is what is copied in your original code) and the cell background colour, then you could use the following code:

Sub Test()
    Dim Range_Grid(1) As Range

    Set Range_Grid(1) = ActiveSheet.Cells(2, 3)
    ActiveSheet.Cells(4, 1) = Range_Grid(1)
    ActiveSheet.Cells(4, 1).Interior.ColorIndex = Range_Grid(1).Interior.ColorIndex
End Sub

Unfortunately there are probably over a dozen types of formatting that you may want to deal with at any given time...

There's an alternative: use Copy and PasteSpecial functions.

Sub Test()

    ActiveSheet.Cells(2, 3).Copy
    ActiveSheet.Cells(4, 1).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