简体   繁体   中英

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

I am trying to compare a string (which could be either a combination of numbers and letters, or just numbers) to a cell that is formatted as text (whose contents could be either a combination of numbers and letters, or just numbers). I am finding that when it is comparing a string with both letters and numbers to the cell with matching contents it is able to correctly identify them as the same. However, when the string contains only numbers is compared to the cell containing identical contents it doesn't recognize it as a match. My code:

If location.Value = identifier then msgbox "Matching"

Where identifier is a string and the cell at location is formatted as text.

I have also found that if I instead use:

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

that it is then able to recognize when two numbers (stored as strings) are equivalent. Is there anyway to avoid using the extra step of using a string to hold location.value ? And if anyone knew why my original method was failing that would be much appreciated as well. Thanks.

Try this. It will ensure that whatever the value in location is, gets compared as a string.

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" -这样,您始终将字符串与字符串进行比较。

You could use FormulaR1C1 instead of Value to compare.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM