excel - 验证最小和最大数字之间的输入框条目

标签 excel vba

我用了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 test If InputValue = False if you plan to accept 0 as number input. Therefore you need also to test for Booleantype:
    If VarType(InputValue) = vbBoolean
    This is because False is automatically cast to 0.

  • 请注意,我使用了 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/

    相关文章:

    vba - 表保护: UserInterFaceOnly gone

    python - 如何让unoconv在转换为pdf之前自动计算公式?

    vba - VBA的 future 是什么?

    excel - 如何保护工作表名称而不是整个工作表?

    vba - 从 Excel 替换 Word 书签内的图像

    python - 模块 'xlwings' 没有属性 'Book'

    excel - 第 n 次出现 Vlookup

    excel - 尝试插入日期时出现运行时错误 '1004'

    excel - 将代码放入循环中,以便在单击任何鼠标后退出循环

    excel - 昏暗的 ws 作为工作表集 ws=ActiveSheet 给了我 "Type Mismatch"