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