InputBox:只允许一定范围的值

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

例如,我只想让0-100,如果他们input超过100,那么

  1. 自动input默认值(如10)和
  2. 创build一个popup消息,指出应用了默认值。

以下是我到目前为止:

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()方法来构build一个小包装器的function:

 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