Excel vba if operator is broken

I can’t figure out what’s wrong with this simple if a < b statement.
The txtMax is 100 whiletxtSafety is 50, when txtMax is lower thantxtSafety then run some error msgbox.

       With Me
              If .txtMax.Value < .txtSafety.Value Then
                     MsgBox "Error"
                     Exit Sub
              End If
       End With

In this case, it should not run the error msgbox since max is higher than safety.
Please help…

>Solution :

They’re almost certainly strings which, when compared, use lexicographical sorting.

In other words, it checks character by character until there’s a difference:

100
50

Since 5 is a larger character value than 1, 50 is considered the greater of the two.

If you want to compare them as if they were numeric values, you should probably convert them into numerics forst, with something like:

With Me
    if CInt(.txtMax.Value) < CInt(.txtSafety.Value) Then

Or turn them into numerics as quickly as possible if you never need to worry about the strings again:

With Me
    maxValue = CInt(.txtMax.Value)
    safetyValue = CInt(.txtSafety.Value)
    if maxValue < safetyValue Then

Leave a Reply