我用了InputBox
对于“期间”,即月份(“m”)。
当我尝试将它用于“年”(“YYYY”)时,它没有按预期运行。
我的“年份”代码(与“期间”相同,只有不同的值和变量):
Dim VYear as variant
Dim defY as variant
defY = Format(DateAdd("YYYY", 0, Now), "YYYY")
VYear = InputBox("Year covered","Year",defY)
If VYear > 2014 And VYear < defY Then
Range("I1").Value = VYear
ElseIf VYear = "" Then
Exit Sub
Else
Do Until VYear > 2014 And VYear < defY
MsgBox "Please enter a year not earlier than 2015 and not later than this year"
VYear = InputBox("Year covered")
Loop
End If
它确实给了我 2018 的默认值。当我尝试输入错误的值时,它会继续显示
MsgBox
中的消息正如预期的那样,但它不再接受任何值,即使是“2018”年。循环:
MsgBox
(请输入....)然后InputBox
然后 MsgBox
再次。我故意用了
As Variant
这样即使用户输入了字母,也不会出现“类型不匹配”的错误。
最佳答案
它应该看起来像这样……
Option Explicit
Public Sub AskForYear()
Dim InputValue As Variant 'needs to be variant because input is FALSE if cancel button is pressed
Dim DefaultYear As Integer
DefaultYear = Year(Date) 'Get the year of the current date today
Do
InputValue = Application.InputBox(Prompt:="Please enter a Year between 2015 and " & DefaultYear & "." & vbCrLf & "Year covered:", Title:="Year", Default:=DefaultYear, Type:=1)
If VarType(InputValue) = vbBoolean And InputValue = False Then Exit Sub 'cancel was pressed
Loop While InputValue < 2015 Or InputValue > DefaultYear
Range("I1").Value = InputValue 'write input value
End Sub
Do
至少运行一次的循环(注意条件在 Loop While
部分)。它一直要求在 2015 年到今年之间的日期,直到满足标准。然后它将继续写入范围。 This is just hypothetical for your specific case (asking for a year) but …
For this criteria it is not sufficient to testIf InputValue = False
if you plan to accept0
as number input. Therefore you need also to test forBoolean
type:
If VarType(InputValue) = vbBoolean
This is becauseFalse
is automatically cast to0
.
Application.InputBox
而不是 InputBox
.这是两个完全不同的:Application.InputBox(Prompt, Title, Default, Left, Top, HelpFile, HelpContextID, Type)
'see the different parameters
InputBox(Prompt, Title, Default, XPos, YPos, HelpFile, Context) As String
在
Application.InputBox
您可以提供 Type
我设置为 1
的参数这意味着它只接受数字(见 Application.InputBox Method )。只需 InputBox
你不能做这个。 Variant
如果真的有必要。在这种情况下,因为 Application.InputBox
可以返回 Boolean
(取消按钮)或数字(输入)。 Range
指定工作表。喜欢 Worksheets("Sheet1").Range("I1")
否则 Excel 会猜测您指的是哪个工作表,它可能很容易失败。 关于excel - 验证最小和最大数字之间的输入框条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52848823/