Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Excel VBA - Why does this arithmetic comparison of a split string containing numbers work?

Tags:

excel

vba

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:

  • 12 isn't larger than 20
  • 9 isn't larger than 20
  • 30 is larger than 20

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

like image 756
Chri.s Avatar asked Jan 29 '23 15:01

Chri.s


2 Answers

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.

enter image description here

*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.

enter image description here

like image 123
TomJohnRiddle Avatar answered Jan 31 '23 04:01

TomJohnRiddle


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
like image 27
shrivallabha.redij Avatar answered Jan 31 '23 05:01

shrivallabha.redij