2016-09-21 89 views
0

我想限制用户可以输入的可接受值的范围。InputBox:只允许一定范围的值

举例来说,我只想让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 

回答

0

我会做这样的:

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 
+2

仅供参考'IsNumeric(CO2PriceBox)'已过时,因为所有非数字值都会在符号'<(因为无法比较)触发VBA错误。尽管如此,默认情况下,使用'Type.Inc ='的'Application.InputBox'可以避免这种情况。 ;) –

+0

谢谢!这个解决方案几乎是完美的,但有一个小问题:我完全按照规定键入了它,并且工作顺利,但如果输入的值超出范围,它实际上并不会将单元格中的值恢复为默认值(10) 。它在对话框中纠正它,但不是实际的单元格。有什么建议?谢谢! – user6851629

+0

没关系,问题解决了!我只需要在指示宏使用默认值的行之后添加“Range(”C11“)。Value = CO2PriceBox”。谢谢! – user6851629

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