我想限制用户可以输入的可接受值的范围。
例如,我想只允许0-100,如果输入超过100,那么
这是我到目前为止所拥有的:
Dim CO2PriceBox As Variant
CO2PriceBox = InputBox("Please Enter CO2 Allowance Price ($/ton)", "Enter CO2 Allowance Price", 0)
Range("C11").Value = CO2PriceBox
答案 0 :(得分:1)
我会这样做:
Dim CO2PriceBox As Variant
CO2PriceBox = InputBox("Please Enter CO2 Allowance Price ($/ton)", "Enter CO2 Allowance Price", 0)
If Not IsNumeric(CO2PriceBox) Or CO2PriceBox < 0 Or 100 < CO2PriceBox Then 'If value out of specified range
CO2PriceBox = 10 'Default value
MsgBox "You Entered a wrong value, using default", vbOKOnly
End If
答案 1 :(得分:1)
您可以使用Excel InputBox()方法构建一个小的“包装器”函数:
Function GetValue(prompt As String, title As String, minVal As Long, maxVal As Long, defVal As Long) As Variant
GetValue = Application.InputBox(prompt & "[" & minVal & "-" & maxVal & "]", title, Default:=defVal, Type:=1)
If GetValue < minVal Or GetValue > maxVal Then
GetValue = defVal
MsgBox "your input exceeded the range: [" & minVal & "-" & maxVal & "]" & vbCrLf & vbCrLf & "the default value (" & defVal & ") was applied", vbInformation
End If
End Function
并按如下方式使用:
Option Explicit
Sub main()
Range("C11").Value = GetValue("Please Enter CO2 Allowance Price ($/ton)", "Enter CO2 Allowance Price", 0, 100, 10)
End Sub