Liam_Sheridan
Liam_Sheridan

Reputation: 17

Use an if statement on a Text Box

I am making a user entry form where they have to enter some figures. I would like them to only enter a number between 2.4 and 6. How can I do this?

My code at the moment is this:

Private Sub txtHeight_Change()
    HeightNumber = CStr(Val(Me.txtHeight.Value))

If HeightNumber >= 2.4 And HeightNumber <= 6 Then
    Else
        MsgBox ("You have entered an incorrect number")
End If

totcost = painttype + undercost + HeightNumber
        TotalCost.Value = totcost
End 

Thanks in advance.

Upvotes: 0

Views: 148

Answers (2)

Noldor130884
Noldor130884

Reputation: 994

Quoting ImClarky

Why not simply convert to double the numeric string and perform the check?

Because of the CDbl, an empty string will always trigger an error (especially because the Macro works for every change in the string as I understood). You can error-handle it with a On Error Goto the end of the Sub, or you could simply check if the string = "". In that case don't execute the Sub.

Let's say the txtHeight was a textbox

Private Sub txtHeight_Change()

If Not Me.txtHeight = "" Then  

    If CDbl(Me.txtHeight) >= 2.4 And CDbl(Me.txtHeight) <= 6 Then
        ' Put your code here, I think those following belong here too
        totcost = painttype + undercost + CDbl(Me.txtHeight)
        TotalCost.Value = totcost
    Else
        MsgBox ("You have entered an incorrect number")
    End If

End If    

End Sub

(This was NOT TESTED)

Upvotes: 0

ImClarky
ImClarky

Reputation: 1953

Not entirely sure if this will solve the problem, but the variable HeightNumber has been converted to a String (CStr). This then makes the operators in you If statement (<= and >=) not work as they don't work with String variables.

Upvotes: 1

Related Questions