Formatting MM/DD/YYYY dates in textbox in VBA

前端 未结 9 1830
故里飘歌
故里飘歌 2020-11-22 10:47

I\'m looking for a way to automatically format the date in a VBA text box to a MM/DD/YYYY format, and I want it to format as the user is typing it in. For instance, once the

9条回答
  •  面向向阳花
    2020-11-22 11:24

    While I agree with what's mentioned in the answers below, suggesting that this is a very bad design for a Userform unless copious amounts of error checks are included...

    to accomplish what you need to do, with minimal changes to your code, there are two approaches.

    1. Use KeyUp() event instead of Change event for the textbox. Here is an example:

      Private Sub TextBox2_KeyUp(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
      
          Dim TextStr As String
          TextStr = TextBox2.Text
      
          If KeyCode <> 8 Then ' i.e. not a backspace
      
              If (Len(TextStr) = 2 Or Len(TextStr) = 5) Then
                  TextStr = TextStr & "/"
              End If
      
          End If
          TextBox2.Text = TextStr
      End Sub
      
    2. Alternately, if you need to use the Change() event, use the following code. This alters the behavior so the user keeps entering the numbers, as

      12072003
      

    while the result as he's typing appears as

        12/07/2003
    

    But the '/' character appears only once the first character of the DD i.e. 0 of 07 is entered. Not ideal, but will still handle backspaces.

        Private Sub TextBox1_Change()
            Dim TextStr As String
    
            TextStr = TextBox1.Text
    
            If (Len(TextStr) = 3 And Mid(TextStr, 3, 1) <> "/") Then
                TextStr = Left(TextStr, 2) & "/" & Right(TextStr, 1)
            ElseIf (Len(TextStr) = 6 And Mid(TextStr, 6, 1) <> "/") Then
                TextStr = Left(TextStr, 5) & "/" & Right(TextStr, 1)
            End If
    
            TextBox1.Text = TextStr
        End Sub
    

提交回复
热议问题