excel - 使用 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
可以工作,但一旦使用多个列源,它似乎就会崩溃。
感谢您的时间!我非常感谢有关此主题的任何帮助。
解决方案
如果指定范围内的所有单元格的数字格式不同,则此属性返回Null 。
如果您的列具有不同的数字格式,那么假设您不想使用剪贴板,则必须像上一种方法一样循环它们。
推荐阅读
- html - 在html中居中按钮
- javascript - NPM Jquery 客户端与服务器端
- java - 尝试将 CSS 与 JavaFx 一起使用,但出现错误
- python - 将具有包含列表的单列的系列拆分为具有单个值的多列
- r - 我如何使用类似 a:b 的表达式按名称对变量子集进行 rowSum
- json - 在 Swift 中解析具有多个相同标识符的 JSON
- python - 为什么我收到以下代码的“HTTPError: HTTP Error 404: Not Found”?
- react-native - 更新购物车商品编号而不是附加新商品
- c# - 访问令牌已过期,无法刷新。错误:刷新错误、刷新错误、刷新错误
- discord - 机器人如何在不重复或循环代码的情况下一遍又一遍地说出消息