如您所说,要将带有格式化文本的 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 查尔斯·威廉姆斯)