【问题标题】:InputBox: Only allow certain range of valuesInputBox:只允许特定范围的值
【发布时间】:2016-09-21 05:11:56
【问题描述】:

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

例如,我只想允许 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

【问题讨论】:

    标签: vba excel inputbox


    【解决方案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
    

    【讨论】:

    • 仅供参考:IsNumeric(CO2PriceBox) 已过时,因为所有非数字值都会在&lt; 符号处触发 VBA 错误(因为无法比较)。尽管如此,默认情况下使用Application.InputBoxType:=1 可以避免这种情况。 ;)
    • 谢谢!这个解决方案几乎是完美的,但有一个小问题:我完全按照说明输入它并且它工作顺利,但如果输入的值超出范围,它实际上不会将单元格中的值恢复为默认值 (10) .它在对话框中更正它,但不是实际的单元格。有什么建议吗?谢谢!
    • 没关系,问题解决了!我只需要在指示宏使用默认值的行之后添加“Range("C11").Value = CO2PriceBox”。谢谢!
    【解决方案2】:

    您可以使用 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-23
      • 1970-01-01
      • 1970-01-01
      • 2019-08-12
      • 1970-01-01
      • 2020-01-13
      • 1970-01-01
      • 2013-11-03
      相关资源
      最近更新 更多