简体   繁体   中英

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

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

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://docs.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 ie

If CInt(arr(i)) > num Then

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