在文本框上使用if语句

我正在做一个用户input表格,他们必须input一些数字。 我希望他们只input一个介于2.4和6之间的数字。我该怎么做?

我现在的代码是这样的:

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 

提前致谢。

引用ImClarky

为什么不简单地转换为数字string的两倍,并执行检查?

由于CDbl ,一个空string总是会触发一个错误(特别是因为macros按照我理解的对string的每一个改变都适用)。 你可以错误地处理它与一个On Error Goto Sub的结尾,或者你可以简单地检查string=“”。 在这种情况下,不要执行Sub。

假设txtHeight是一个文本框

 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 

(这不是testing)

不完全确定这是否会解决问题,但variablesHeightNumber已被转换为string(CStr)。 这使得在你的操作符If语句( <=>= )不起作用,因为他们不使用stringvariables。