首页 > 解决方案 > 使用嵌套 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,然后运行测试以查看它是否是

  1. 正好 10 个字符长
  2. 之前或今天的日期

在任何时候,如果它没有通过这两个测试,DateOfJob 将给出一个文本值,这将导致最终的 IsDate 测试失败。

但是,无论输入什么,我都觉得它正在通过文本,因此完全没有通过测试。

提前感谢您的帮助。

标签: vbaoutlook

解决方案


输入字符串的长度没有区别:您正在查看日期,或者您不是:您希望其余代码使用该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按钮,用户会期望它取消操作:不要否认他们的能力 - 优雅地处理它反而。


推荐阅读