【问题标题】:Pasting Values as Displayed粘贴显示的值
【发布时间】:2022-08-12 18:58:44
【问题描述】:

我在 excel 中有一列具有以下格式的单元格:\"0000.00\" 仅供参考,引号不是格式的一部分。

基本上,四位数字后跟两位小数。但是,当数字为“600”时,需要显示为“0600.00”。但是,提供给我的数字列表是通过格式化显示的,所以如果我尝试 VLOOKUP,它无法处理它;它看到的是“600”,而不是显示给我的“0600.00”。

我知道PasteSpecial Paste:=xlPasteValues,但这会粘贴“600”,而不是显示给我的“0600.00”。目前,我可以通过复制值并将它们粘贴到记事本中来实现这样的结果——这对我来说是一种方法——但我想创建一个宏来为我做这件事。

抱歉有任何多余的解释,只是想避免获得与粘贴值有关的答案,这不是我想要的。

  • Excel 将单元格值和格式存储为两个独立的东西。如果将值复制到新单元格,则还需要复制格式。值为600,格式为0000.00。尝试使用Cell.NumberFormat = \"0000.00\",你会看到显示值变成了\"0600.00\"
  • 我没有 Excel,所以无法测试 - 但我似乎记得 \"xlPasteValuesAndNumberFormats\"

标签: excel vba


【解决方案1】:

如您所说,要将带有格式化文本的 VLOOKUP 用作查找值,您需要单元格的值与查找值的值匹配,因此您必须将单元格中的值转换为带有某些内容的文本像这样(单个单元格的示例):

Dim rng As Range
Set rng = Range("A1")

rng.PasteSpecial xlPasteFormulasAndNumberFormats

Dim TextValue As String
TextValue = Format(rng, rng.NumberFormat)

rng.NumberFormat = "@" 'We need this line to turn the cell content into text
rng.Value2 = TextValue 

我很确定没有 PasteSpecial 选项将允许您在单个操作中执行您想要的操作,因此此解决方案是一种解决方法,它分两步完成。

多格情况:

我意识到上面的代码没有解决粘贴多个单元格的问题,所以这里有一个程序可以用来将格式化的数字作为文本从一个范围复制到另一个范围:

Sub CopyAsFormattedText(ByRef SourceRange As Range, ByRef DestinationRange As Range)
   
    'Load values into an array
    Dim CellValues() As Variant
    CellValues = SourceRange.Value2
       
    'Transform values using number format from source range
    Dim i As Long, j As Long
    For i = 1 To UBound(CellValues, 1)
        For j = 1 To UBound(CellValues, 2)
            CellValues(i, j) = Format(CellValues(i, j), SourceRange.Cells(i, j).NumberFormat)
        Next j
    Next i
    
    'Paste to destination by using the top left cell and resizing the range to be the same size as the source range
    Dim TopLeftCell As Range
    Set TopLeftCell = DestinationRange.Cells(1, 1)
    
    Dim PasteRange As Range
    Set PasteRange = TopLeftCell.Resize(UBound(CellValues, 1), UBound(CellValues, 2))
    PasteRange.NumberFormat = "@" 'We need this line to turn the cells content into text
    PasteRange.Value2 = CellValues
    
End Sub

这基本上是相同的想法,但有一个循环。

请注意,如果格式始终相同,您可以将其设为变量并将其应用于数组中的每个值,而不是在每个单元格上调用 .NumberFormat,这不可避免地会增加一点开销。

边注

有人可能会问为什么我不建议使用:

SourceRange.Cells(i, j).Text

代替

Format(CellValues(i, j), SourceRange.Cells(i, j).NumberFormat)

这将是一个非常好的问题!我想,.Text 可以在列大小不正确时返回“###...”这一事实总是让我害怕使用它,但它在代码中肯定会看起来更清晰。但是,我不确定在性能方面会更好。 (Relevant article 查尔斯·威廉姆斯)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-02
    相关资源
    最近更新 更多