防止用户在用户表单中输入之前的日期

preventing user from entering prior date in userform

我试图阻止用户在用户表单顶部的文本框中输入早于今天的生效日期。

这里的逻辑似乎很合适,但即使日期晚于今天,我也会收到消息框。

Private Sub txtEffective_Date_Change()
    If IsDate(txtEffective_Date) Then
        If cdate(txtEffective_Date) < Date Then
            MsgBox "Date chosen is prior to today's date"
        End If
    End If
End Sub

我认为这与 cdate 对比 date 有关,但不完全确定这里出了什么问题。

每次击键都会触发更改事件,从而导致您遇到的问题。只需将此代码移动到另一个事件,例如 LostFocus 或 Validate,就可以了。

编辑:由于这是 VBA 而不是 VB6,请尝试退出事件。

对于任何试图在更改事件中执行此操作的人。在进行比较之前,您需要先确保您的日期是正确的。例如5/5 输入在 CDate 上变为 2020 年 5 月 5 日。等待输入正确再比较

Private Sub TextBox1_Change()
    Dim sDate As String
        
    If TextBox1.Text Like "??[/-]??[/-]????" Or _
        TextBox1.Text Like "?[/-]?[/-]????" Or _
        TextBox1.Text Like "?[/-]??[/-]????" Or _
        TextBox1.Text Like "??[/-]?[/-]????" Then
        
        sDate = Format(CDate(TextBox1.Text), "dd/MMM/YYYY")
    Else
        Exit Sub
    End If
    
    If IsDate(sDate) Then
        If CDate(sDate) < Date Then
            MsgBox "Previous date is not allowed...." + sDate
        End If
    End If
End Sub