gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 22:31:00 25 4
gpt4 key购买 nike

我用了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/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com