我在 excel 中有一列具有以下格式的單元格:“0000.00”僅供參考,引號不是格式的一部分。
基本上,四位數字后跟兩位小數。但是,當數字像“600”時,它們需要顯示為“0600.00”。但是,提供給我的數字串列是通過格式化顯示的,所以如果我嘗試 VLOOKUP,它無法處理它;它看到的是“600”,而不是顯示給我的“0600.00”。
我知道PasteSpecial Paste:=xlPasteValues,但這會粘貼“600”,而不是顯示給我的“0600.00”。目前我可以通過復制值并將它們粘貼到記事本中來實作這樣的結果——這對我來說是一種方法可以做到這一點——但我想創建一個宏來為我做這件事。
抱歉有任何多余的解釋,只是想避免獲得與粘貼值有關的答案,這不是我想要的。
uj5u.com熱心網友回復:
如您所說,要將帶有格式化文本的 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我想,當列大小不正確時可以回傳“###...”的事實總是讓我害怕使用它,但它在代碼中肯定會看起來更清晰。但是,我不確定在性能方面會更好。(查爾斯·威廉姆斯的相關文章)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/485928.html
