首页 > 解决方案 > 使用 Excel VBA 是否可以将整个工作表的 NumberFormat 复制到新工作表?

问题描述

在 Excel 中,有没有办法将 NumberFormat 从具有多列的输入范围复制到具有相同列数的输出范围?

我已经尝试了此代码示例中的几个变体,但是当我尝试从多个列中获取输出范围的格式时,输出范围的格式没有变化,或者复制值的性能太成问题。

Sub Import()
    'Demonstration variables
    Dim ws_input As Worksheet: Set ws_input = ThisWorkbook.Sheets(1)
    Dim ws_output As Worksheet: Set ws_output = ThisWorkbook.Sheets(2)
    Dim rowLast As Double, colLast As Double, i As Double

    rowLast = ws_input.Cells(Rows.Count, 1).End(xlUp).Row
    colLast = ws_input.Cells(1, Columns.Count).End(xlToLeft).Column

    'This variant is way too much of a performance hit and Excel can misapply formatting
    'E.g. Cell XFD1048576 is considered used
    ws_input.Cells.Copy Destination:=ws_output.Range("A1")

    'This variant can copy "###" as the value if the input cell widths are too small
    ws_output.Range("A1", Cells(rowLast, colLast).Address).Value = _
        ws_input.Range("A1", Cells(rowLast, colLast).Address).Value

    'This variant copies values correctly but without formatting
    ws_output.Range("A1", Cells(rowLast, colLast).Address).Value2 = _
        ws_input.Range("A1", Cells(rowLast, colLast).Address).Value2
    ws_output.Range("A1", Cells(rowLast, colLast).Address).NumberFormat  = _
        ws_input.Range("A1", Cells(rowLast, colLast).Address).NumberFormat

    'This variant also seemingly does nothing with the NumberFormat
    ws_output.Range("A1", Cells(rowLast, colLast).Address).EntireColumn.NumberFormat  = _
        ws_input.Range("A1", Cells(rowLast, colLast).Address).EntireColumn.NumberFormat

    'This variant also seemingly does nothing with the NumberFormat
    ws_output.Range("A1").CurrentRegion.NumberFormat = _
        ws_input.Range("A1").CurrentRegion.NumberFormat

    'Kludgy solution I've come to
    For i = 1 to colLast
        ws_output.Columns(i).NumberFormat = ws_input.Columns(i).NumberFormat
    Next i
End Sub

我希望避免每次需要应用数字格式时都必须使用迭代器,而且似乎应该有一种更直观的方式让 Excel 可以将 NumberFormat 属性应用于多个范围中的多个范围。如果我只想获取一个范围作为格式,ws_output.Range("A1:Z9999").NumberFormat = ws_input.Range("A1").NumberFormat可以工作,但一旦使用多个列源,它似乎就会崩溃。

感谢您的时间!我非常感谢有关此主题的任何帮助。

标签: excelvbanumber-formatting

解决方案


Range.NumberFormat文档:

如果指定范围内的所有单元格的数字格式不同,则此属性返回Null 。

如果您的列具有不同的数字格式,那么假设您不想使用剪贴板,则必须像上一种方法一样循环它们。


推荐阅读