Search code examples
vbacomparison

How do I compare values in VBA?


I have this Sub. It is activated when pressing a button on a user form and is used to count one entry up. I have the total amount of entries in this data base stored in A1. There is another button used to count one entry down, it works just fine. They both have checks so they don't load entries that don't exist. Somehow this one doesn't work.

Private Sub ButtonRight_Click()
    
    MsgBox TextBoxID.Value
    MsgBox Cells(1, 1).Value
    MsgBox (TextBoxID.Value < Cells(1, 1).Value)
    If TextBoxID.Value < Cells(1, 1).Value Then
        LoadEntry (TextBoxID.Value + 1)
    End If

End Sub

The LoadEntry Sub is used in other places as well and it works. I have this output stuff with MsgBox for debugging. It gives the outputs 1, 2, false. So (1 < 2) = false.

For comparison here is the other one which works:

Private Sub ButtonLeft_Click()
    
    If TextBoxID.Value > 1 Then
        LoadEntry (TextBoxID.Value - 1)
    End If
    
End Sub

Solution

  • The problem is implicit conversions.

    Strings are compared as text, so "10" is smaller than "2" because it sorts alphabetically as such.

    Debug.Print "10" > "2" ' output: False
    

    The value of a TextBox control is always a String; in order to treat it as a numeric value you must first convert it to a numeric value - but only if it's legal to do so (e.g. "ABC" has no equivalent numeric value).

    Moreover, a cell's value is a Variant that may contain a number or another value that can (will) correctly but implicitly convert to a numeric value, but it could also be a Variant/Error (e.g. #N/A, or #VALUE! errors) that will throw a type mismatch error every time you try to compare it to anything (other than another Variant/Error value), so the cell's value should also be validated and explicitly converted before it's compared:

    Dim rawValue As String
    rawValue = TextBoxID.Value
    
    If IsNumeric(rawValue) Then
        Dim numValue As Double
        numValue = CDbl(rawValue)
    
        Dim cellValue As Variant
        cellValue = ActiveSheet.Cells(1, 1).Value
    
        If IsNumeric(cellValue) Then
            If numValue < CDbl(cellValue) Then
                LoadEntry numValue + 1
            End If
        End If
    
    End If
    

    Note that unqualified, Cells is implicitly referring to whatever the ActiveSheet happens to be - if that isn't the intent, consider qualifying that member call with an explicit Worksheet object, e.g. Sheet1.Cells(1, 1). If it is intentional, consider qualifying it with ActiveSheet so that the code says what it does, and does what it says.