InputBox:只允许特定范围的值

InputBox: Only allow certain range of values

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

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

  1. 自动输入一个默认值(比如10)和
  2. 创建一条弹出消息,指示已应用默认值。

这是我目前的情况:

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

我会这样做:

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

您可以使用 Excel InputBox() 方法构建一个小 "wrapper" 函数:

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