在VBA中复制样式时维护目标数据格式?

时间:2018-01-10 13:57:00

标签: excel vba excel-vba

我正在尝试将样式从特定列(格式为文本从第二行开始)复制到另一列(格式为日期从第二行开始) )。两列都存储值。

我可以将样式复制并粘贴到目标列:

.Columns("A").Copy '# "A" is the starting column
.Columns(dest_col).PasteSpecial Paste:=xlPasteFormats '# dest_col is the destination column

但是此代码也将其格式化为Text列,而我想保留其原始格式(即Date从第二行开始)。

我可以使用任何选项来阻止此行为吗?

1 个答案:

答案 0 :(得分:1)

您可以尝试仅拍摄您感兴趣的特定参数的值(例如,样式,内部颜色,字体颜色等)

以下内容仅适用于整列具有相同格式的情况,只要我没有遍历每个单元格:

Option Explicit

Sub TestMe()

    Dim colFrom     As Long
    Dim colTo       As Long

    colFrom = 1
    colTo = 5
    CopyFullFontAndInterior colFrom, colTo

End Sub

Sub CopyFullFontAndInterior(colFrom As Long, colTo As Long, Optional wsN As Long = 1)

    Dim copyFrom    As Range
    Dim copyTo      As Range

    With Worksheets(1)
        Set copyFrom = .Range(.Cells(1, colFrom), .Cells(2 ^ 20, colFrom))
        Set copyTo = .Range(.Cells(1, colTo), .Cells(2 ^ 20, colTo))
    End With

    copyTo.Style = copyFrom.Style
    If copyFrom.Interior.Color > 0 Then copyTo.Interior.Color = copyFrom.Interior.Color
    If copyFrom.Font.Color > 0 Then copyTo.Font.Color = copyFrom.Font.Color

End Sub

一种可行的解决方法是将列中给定单元格的格式保存在变量中,并在.PasteSpecial之后使用它:

Sub TestMe()

    Dim saveOurFormat As String

    saveOurFormat = Columns(5).Cells(2).NumberFormat
    Columns("A").Copy
    Columns(5).PasteSpecial Paste:=xlPasteFormats
    Columns(5).NumberFormat = saveOurFormat
    Application.CutCopyMode = False

End Sub