仅允许在VBA中输入特定范围的数字

时间:2014-07-14 11:12:21

标签: excel vba excel-vba

我目前正在制作一个弹出式菜单'在VB中。

其中一个要求是只允许在房间的高度范围内输入2.4到6之间的数字" (见下面的代码)。

我不确定如何做到这一点,并且非常感谢任何帮助。到目前为止,我的代码看起来像这样:

Sub WallPaint()
    num1 = Val(InputBox("Enter the height of the room"))
    num2 = Val(InputBox("Enter the width of the first wall"))
    num3 = Val(InputBox("Enter the width of the window"))

    ans = (num1 * num2) - num3

    MsgBox "The area of the room is " & ans
End Sub

好的,多亏了Sujith我现在知道了布局。但是我需要为很多队伍做这件事。是否有更好的方法来布置数据而不是:

    Sub WallPaint()

num1 = Val(InputBox("Enter the height of the room"))    
If num1 > 2.4 And num1 < 6 Then    
Else    
MsgBox ("It is not a valid input")    
End If    
num2 = Val(InputBox("Enter the width of the first wall"))    
If num2 > 1 And num2 < 25 Then    
Else    
MsgBox ("It is not a valid input")    
End If    
num3 = Val(InputBox("Enter the width of the second wall"))    
If num3 > 1 And num2 < 25 Then    
Else    
MsgBox ("It is not a valid input")    
End If    
num4 = Val(InputBox("Enter the width of the third wall"))    
If num4 > 1 And num2 < 25 Then    
Else    
MsgBox ("It is not a valid input")    
End If    
num5 = Val(InputBox("Enter the width of the fourth wall"))    
If num5 > 1 And num2 < 25 Then    
Else    
MsgBox ("It is not a valid input")    
End If    
num6 = Val(InputBox("Enter the height of the window"))    
If num6 > 0.9 And num6 < 1.5 Then    
Else    
MsgBox ("It is not a valid input")    
End If    
num7 = Val(InputBox("Enter the width of the window"))    
If num7 > 0.9 And num7 < 2 Then    
Else    
MsgBox ("It is not a valid input")    
End If    
ans = (num2 * num3 * num4 * num5) + num1 - (num6 * num7)    
MsgBox ("The size of your room is " & ans)    
    End Sub

再次感谢。

2 个答案:

答案 0 :(得分:0)

我认为在输入数据库值之前验证输入更好,可以使用

num1 = Val(InputBox("Enter the height of the room"))
if num1>2.4 and num1<6 then
num2 = Val(InputBox("Enter the width of the first wall"))
num3 = Val(InputBox("Enter the width of the window"))
else
msgbox("It is not a valid input")
end if

答案 1 :(得分:0)

public sub check(n1 as double,n2 as double,a as double,b as double)
If n1 > a And n2 < b Then    
'code comes here
Else    
MsgBox ("It is not a valid input")    
End If   
end sub

在需要条件检查时调用该函数;像这样打电话

check(num1,num2,2.5,6)' instead of first if