日期范围输入VBA

时间:2019-06-17 10:06:46

标签: excel vba date range

我必须处理开始日期和结束日期。

用户必须将其以格式“ mm”和“ yyyy”的形式输入到用户表单的文本框中。我已将每个文本框的文本限制分别设置为2和4。

用户键入2位数字后,焦点应转到下一个框。我该如何实现?

因为会有开始日期和结束日期:如何循环显示所有数据,例如G。从201702到201904?

1 个答案:

答案 0 :(得分:1)

尝试以下方法。这将检查文本框是否包含两个字符以及是否包含数字值。然后,将焦点设置到第二个文本框

Private Sub TextBox1_KeyUp(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
If Not (KeyCode = vbKeyBack Or KeyCode = vbKeyDelete Or (47 < KeyCode And KeyCode < 58) Or (95 < KeyCode And KeyCode < 106)) Then
    If Len(Me.TextBox1.Value) = 1 Then
        Me.TextBox1.Value = ""
    Else
        Me.TextBox1.Value = Left(Me.TextBox1.Value, 1)
    End If
End If
If Len(Me.TextBox1) = 2 And IsNumeric(Me.TextBox1) Then
    Me.TextBox2.SetFocus
End If
End Sub

可以如下遍历日期范围

Sub loopthroughdates()
Dim d As Date
For d = DateSerial(Year(Now), Month(Now), Day(Now)) To DateSerial(2020, 1, 1)
    'Do stuff
Next d
End Sub