I'm wondering why the below code works as I hoped for, considering that I'm splitting a string into an array (that's also defined as a string), and afterwards comparing it in an arithmetic (numeric) way.
Option Explicit
Sub test()
Dim str As String, arr() As String
Dim num As Integer, i As Integer
str = "12 9 30"
num = 20
arr() = Split(str, " ")
For i = LBound(arr) To UBound(arr)
If arr(i) > num Then
MsgBox (arr(i) & " is larger than " & num)
End If
Next i
End Sub
As intended the msgBox
within the if statement
is fired, showing that:
I didn't know/think that such comparison could work as hoped as i'm basically comparing a string to an integer. I assume there's something i'm not aware of, but in that case, what is it?
PS. I was a bit in doubt regarding which forum to post in, but based my choice on this meta question
For answer please refer to the following article: https://msdn.microsoft.com/en-us/library/aa263418(v=vs.60).aspx
In short if you compare string to numeric type variable, string variable is converted to double* type.
*double based on the information from VB .net comparison operators reference (https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/operators/comparison-operators), VB 6.0, VBA and VBA .net are not the same things, however comparison logic should be the same.
VBA seems to be implicitly converting the data type during run-time.
Consider following code which also works.
Sub test2()
Dim str As String, arr() As String, num As String
Dim i As Integer
str = "12 9 30"
num = 12 '\\ Note the way number is being passed.
arr() = Split(str, " ")
For i = LBound(arr) To UBound(arr)
If arr(i) = num Then
MsgBox (arr(i) & " is equal to " & num)
End If
Next i
End Sub
And then below one where arithmetic operation is coercing it to be numeric at run-time.
Sub test3()
Dim str As String, arr() As String, num As String
Dim i As Integer
str = "12 9 30"
num = 12
arr() = Split(str, " ")
For i = LBound(arr) To UBound(arr)
If (arr(i) - num) > 0 Then
MsgBox (arr(i) & " is greater than " & num)
End If
Next i
End Sub
I know it will not answer your question fully but might explain why it is giving correct result. It is advisable to convert to correct data type rather than relying on defaults i.e.
If CInt(arr(i)) > num Then
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With