Formatting MM/DD/YYYY dates in textbox in VBA

前端 未结 9 1747
故里飘歌
故里飘歌 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:08

    For a quick solution, I usually do like this.

    This approach will allow the user to enter date in any format they like in the textbox, and finally format in mm/dd/yyyy format when he is done editing. So it is quite flexible:

    Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
        If TextBox1.Text <> "" Then
            If IsDate(TextBox1.Text) Then
                TextBox1.Text = Format(TextBox1.Text, "mm/dd/yyyy")
            Else
                MsgBox "Please enter a valid date!"
                Cancel = True
            End If
        End If
    End Sub
    

    However, I think what Sid developed is a much better approach - a full fledged date picker control.

提交回复
热议问题