簡體   English   中英

結合使用VBA和Excel 2007將字符串中存儲的數字與包含以文本格式設置的數字的單元格進行比較

[英]Using VBA with excel 2007 to compare a number stored in a string to a cell which contains a number formatted as text

我正在嘗試將字符串(可以是數字和字母的組合,或者只是數字)與格式化為文本(其內容可以是數字和字母的組合,或者只是數字)的單元格進行比較。 我發現當將帶有字母和數字的字符串與具有匹配內容的單元格進行比較時,它能夠正確地將它們標識為相同。 但是,如果將僅包含數字的字符串與包含相同內容的單元格進行比較,則不會將其識別為匹配項。 我的代碼:

If location.Value = identifier then msgbox "Matching"

其中identifier是一個字符串, location處的單元格設置為文本格式。

我還發現,如果我改用:

Dim ID_holder As String
ID_holder = location.value
If ID_holder = identifier then msgbox "Matching"

這樣便可以識別兩個數字(存儲為字符串)是否相等。 無論如何,有沒有避免使用使用字符串保存location.value的額外步驟? 如果有人知道為什么我的原始方法失敗了,那也將不勝感激。 謝謝。

嘗試這個。 它將確保無論location的值是什么,都將其作為字符串進行比較。

Dim ID_holder As String
ID_holder = cstr(location.value)
If ID_holder = cstr(identifier) then msgbox "Matching"

嘗試If CStr(location.Value) = CStr(identifier) then msgbox "Matching" -這樣,您始終將字符串與字符串進行比較。

您可以使用FormulaR1C1代替Value進行比較。

Sub Macro1()
Set a = Range("A1")
Set b = Range("A2")

If a.FormulaR1C1 = "123" Then MsgBox "a: Match"

If b.FormulaR1C1 = "abc" Then MsgBox "b: Match"

End Sub

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM