VB6 将文本框输入限制为从 1900 年到当前日期范围内的数字?

VB6 limit textbox input to numbers in the range from 1900 to current date?

如何限制文本框输入从 1900 年到当前日期范围内的数字?

Private Sub txtYear_Change()
    If Not IsNumeric(txtYear.Text) Then
        txtYear.Text = ""
    ElseIf txtYear.Text < 1900 Or txtYear.Text > Year(Date) Then
        txtYear.Text = ""
    End If
Exit Sub 

您需要将该代码放在 txtYear_Validate() 事件中,而不是 change 事件中。每次击键都会触发更改,因此几乎总是会立即失败。在验证事件中完成之前不要验证条目。

中所述,您应该使用 Validate 事件。

我只是想补充一点,您的代码仍然存在缺陷,即它会允许用户输入十进制数(例如,1900.10)。为了避免这种情况,您可以添加另一个条件:

Private Sub txtYear_Validate(Cancel As Boolean)
    If Not IsNumeric(txtYear.Text) Then
        txtYear.Text = ""
    ElseIf txtYear.Text < 1900 Or txtYear.Text > Year(Date) Then
        txtYear.Text = ""
    ElseIf Fix(txtYear.Text) <> txtYear.Text Then   ' Choose one:
        txtYear.Text = Fix(txtYear.Text)            ' - Replace it with the integer part.
        'txtYear.Text = ""                          ' - Clear the text.
    End If
End Sub