【发布时间】:2020-03-31 15:21:13
【问题描述】:
在 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 有效,但一旦使用多个列源,它似乎就会崩溃。
感谢您的宝贵时间!我非常感谢有关此主题的任何帮助。
【问题讨论】:
-
您可以复制和粘贴格式。
Range("A1").PasteSpecial xllPasteFormats -
ws_input.UsedRange.Copy Destination:=ws_output.Range("A1")- 不要复制整张纸。"'E.g. Cell XFD1048576 is considered used"- 实际上,ws_input.Cells是整张纸,与是否使用无关。 -
或者使用
rowLast和colLast来划定要复制的范围... -
@BigBen 所以我希望微软在这篇文章上有一个 KB 编号,但基本上 Excel 会误用格式并考虑单元格,即使没有数据,也会一直使用到最后。这是您将看到 40MB 大的工作表的地方。但是出于这个原因,您可以看到第二个变体使用变量来识别要引入的行/列。默认的“复制”功能有很多开销,因为它复制了我们试图避免的所有范围属性。在大文件中,这会对性能造成巨大影响。
-
@BigBen 惊人的收获,我以前看过这些文档,我不敢相信它从未卡住。谢谢!我现在将对一些变体进行一些压力测试,看看什么最适合性能。
标签: excel vba number-formatting