InputBox:仅允许特定范围的值

时间:2016-09-21 05:11:57

标签: excel vba excel-vba inputbox

我想限制用户可以输入的可接受值的范围。

例如,我想只允许0-100,如果输入超过100,那么

  1. 自动输入默认值(例如10)和
  2. 创建一条弹出消息,指示已应用默认值。
  3. 这是我到目前为止所拥有的:

    Dim CO2PriceBox As Variant
        CO2PriceBox = InputBox("Please Enter CO2 Allowance Price ($/ton)", "Enter CO2 Allowance Price", 0)
        Range("C11").Value = CO2PriceBox
    

2 个答案:

答案 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