excel - InputBox 数据验证和结束循环
问题描述
我有一些代码可以通过InputBox
(见下文)输入日期。问题是它Else
不起作用(即,如果用户输入的格式不是 mm/dd/yy 它不会停止)。如何使用户必须以呈现的格式输入它?
另外,我想用endDate
. 现在,如果您输入 01/10/20 作为开始日期并输入 12/31/20 作为结束日期,它将在 2021 年 1 月 1 日停止。如何让它在 2020 年 12 月 31 日停止?
Dim startDate As Date
Dim endDate As Date
startDate = InputBox("Enter project start date in format mm/dd/yy", "User date", Format(Now(), "dd/mm/yy"))
endDate = InputBox("Enter project end date in format mm/dd/yy", "User date", Format(Now(), "dd/mm/yy"))
If IsDate(startDate) Then
startDate = Format(CDate(startDate), "mmm d, yyyy")
Else
MsgBox "Wrong date format"
End If
If IsDate(endDate) Then
endDate = Format(CDate(endDate), "mmm d, yyyy")
Else
MsgBox "Wrong date format"
End If
Range("A2").Value = startDate
Dim i As Long
Dim j As Long
Dim x As Integer
i = startDate
j = endDate
x = 3
Do Until i >= j
Cells(x, 1).Value = i + 7
i = i + 7
x = x + 1
Loop
End Sub```
解决方案
当日期不正确时,它会显示消息框,但在关闭消息框后没有任何东西可以阻止它继续执行代码。有几种方法可以解决此问题。
首先是简单地添加行
Exit Sub
在显示 msgbox 之后。
但是,我假设您不希望程序在输入错误后放弃。相反,您可能希望它通知用户它是不正确的并要求另一个输入,直到他们提供有效的格式。
我通常这样做的方式是使用 Do Until 循环。尝试这个:
startDate = InputBox("Enter project start date in format mm/dd/yy", "User date",
Format(Now(), "dd/mm/yy"))
Do Until IsDate(startDate)
MsgBox "Wrong date format."
startDate = InputBox("Enter project start date in format mm/dd/yy", "User date",
Loop
endDate = InputBox("Enter project end date in format mm/dd/yy", "User date",
Format(Now(), "dd/mm/yy"))
Do Until IsDate(endDate)
MsgBox "Wrong date format."
startDate = InputBox("Enter project start date in format mm/dd/yy", "User date",
Loop
第二个问题是因为您在添加 7之前检查 i 的值。另外,仅当 endDate 与 startDate 相差 7 的倍数时才会打印。如果您总是希望打印结束日期,则必须进行一些更改。
试试这个:
i = startDate + 7
j = endDate
x = 3
Do Until i > j
Cells(x, 1).Value = i
i = i + 7
x = x + 1
Loop
Cells(x, 1).Value = endDate
推荐阅读
- node.js - docker-compose up --build 找不到模块
- reactjs - 为什么在为显示属性等类属性调用 setState 时会出错?
- flutter - 小部件可以有一个“联合”状态吗?
- reactjs - 在单击跨度时,我们如何使用 useRef() 获取正确的跨度名称
- batch-file - 在批处理脚本中替换特殊符号
- python-3.x - 如何在 Python 中接受带有 Selenium 的 cookie 弹出窗口
- amazon-web-services - AWS S3 访问策略 - 限制文件夹访问
- web3 - 转账ERC20代币失败:web3.exceptions.ContractLogicError:执行恢复:ERC20:从零地址转账
- javascript - Stripe - 退款结账环节
- c++ - 有效地找到系列中的第 n 个数字,其中数字只能被 2,3 和 5 整除