使用嵌套的If时如何解决循环错误

时间:2019-09-18 01:07:38

标签: vba outlook

我写了一段代码,目的是检查输入的值是否是日期。该部分工作正常,但是当我添加我认为应该进行验证的内容(例如输入的字符串的长度以及日期是否在今天之前或今天)时,它将变成一个无限循环,我无法逃避。

我尝试了不带循环的代码,它的行为符合预期,但是当我将两者结合时,无限循环返回。

QApplication

我希望代码会进入循环,收集值DateOfJob,然后运行测试以查看是否为

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

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

但是,无论输入什么内容,我都认为它正在通过文本,因此完全无法通过测试。

在此先感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

输入字符串的长度没有区别:您正在看日期还是不在:您希望其余代码使用Date值而不是{{ 1}}用户提供的表示形式。

看看这是否对您有用:

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 具有 Cancel 按钮,用户会期望它取消操作:不要否认他们的这种能力-请妥善处理。

答案 1 :(得分:0)

感谢大家的投入。

最后,我选择了Mathieu Guindon解决方案,并对其进行了少许修改。 他编写的代码不错:)

Do While Not isValid
  Dim userInput As Variant
    userInput = VBA.InputBox("What is the date the work is to be carried out on ? DD/MM/YYYY")
    ' 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:
      End
    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
  DateOfJob = dateValue
Loop