vba - 使用嵌套 If 时如何修复循环错误
问题描述
我写了一段代码,用于检查输入的值是否为日期。这部分工作正常,但是当我添加我认为会进行一些验证的内容(例如输入的字符串的长度以及日期是之前还是今天)时,它变成了一个我无法逃脱的无限循环。
我已经尝试了没有循环的代码,它的行为符合预期,但是当我将两者结合起来时,无限循环返回。
'Checks if the value entered is in a 10 digit date format, after today
Do Until IsDate(DateOfJob)
DateOfJob = InputBox("What is the date the work is to be carried out on ? DD/MM/YYYY")
If Len(DateOfJob) <> 10 Then
DateOfJob = "NotEnoughCharacters"
ElseIf DateOfJob <= Date Then
DateOfJob = "Today"
End If
Loop
我原以为代码会进入循环,收集值 DateOfJob,然后运行测试以查看它是否是
- 正好 10 个字符长
- 之前或今天的日期
在任何时候,如果它没有通过这两个测试,DateOfJob 将给出一个文本值,这将导致最终的 IsDate 测试失败。
但是,无论输入什么,我都觉得它正在通过文本,因此完全没有通过测试。
提前感谢您的帮助。
解决方案
输入字符串的长度没有区别:您正在查看日期,或者您不是:您希望其余代码使用该Date
值,而不是String
用户提供的表示。
看看这是否适合你:
Public Function GetValidDate() As Variant '/Date
Dim isValid As Boolean
Do While Not isValid
Dim userInput As Variant
userInput = VBA.InputBox(...)
' if user cancelled the prompt; we better not prompt again:
If VarType(userInput) = vbBoolean Then
'if we don't assign the result, we yield a Variant/Empty:
Exit Function
End If
If IsDate(userInput) Then
Dim dateValue As Date
dateValue = CDate(userInput) '<~ we know it's valid at this point
isValid = dateValue > VBA.DateTime.Date
End If
Loop
GetValidDate = dateValue
End Function
利用:
'NOTE: As Date would be a *type mismatch* error if GetValidDate is Variant/Empty.
Dim jobStartDate As Variant
jobStartDate = GetValidDate
If Not IsDate(jobStartDate) Then Exit Sub
如果不提供有效的输入值,不要让用户陷入他们无法摆脱的循环 -InputBox
有一个Cancel按钮,用户会期望它取消操作:不要否认他们的能力 - 优雅地处理它反而。
推荐阅读
- javascript - 包含来自 Json 数组的数据的表,如何添加多个子行
- python-3.x - Python中是否有一种方法可以“检查”文本文件是否已被修改或附加?
- r - 这是否模拟了指定的时间序列?
- lisp - “冒号后的非法终止字符:#\”在portacle中,但代码中没有冒号
- c++ - 如何使用断言对数组进行测试?
- haskell - 如何在 Dhall 中表示“Data.Map Text Text”?
- r - purrr 与 pluck 相对(丢弃元素)+ 在 pluck 中保留列表结构
- javascript - 如何用玩笑测试更新组件状态的函数
- python-3.x - Pandas read_csv 方法在使用 ISO 8859-15 编码时无法正确获取“-”字符
- containers - 服务网格与 IBM IIB 或 Oracle ESB 等 2010 年 ESB 解决方案有何不同