Textbox to update into date format

Patriot2879

Well-known Member
Joined
Feb 1, 2018
Messages
1,259
Office Version
  1. 2010
Platform
  1. Windows
Hi, good afternoon, i have the code below, where if i enter a date into the text box like 121219 or 12122019 it should convert to 12/12/2019 but it doesn't it either says date incorrect or change it to 23/23/2023 which is wrong, please can you help.
Code:
Private Sub TextBox1_BeforeUpdate(ByVal Cancel As MSForms.ReturnBoolean)
 Dim dtTmp As Date
 Cancel = False
 On Error GoTo err_baddate
 dtTmp = CDate(Me.TextBox1.Text)
 Me.TextBox1.Text = dtTmp
 On Error GoTo 0
sub_ex:
 Exit Sub
err_baddate:
 MsgBox "Bad date", vbOKOnly + vbExclamation
 Cancel = True
 Resume sub_ex
 End Sub
 

Excel Facts

Best way to learn Power Query?
Read M is for (Data) Monkey book by Ken Puls and Miguel Escobar. It is the complete guide to Power Query.
Please try this:

Code:
Private Sub TextBox1_BeforeUpdate(ByVal Cancel As MSForms.ReturnBoolean)  Dim A As String
 
  A = TextBox1.Text
  
  If IsDate(TextBox1.Value) Then
    Exit Sub
  ElseIf Len(TextBox1.Text) = 8 And InStr("/", A) = 0 Then
    TextBox1.Text = Left(A, 2) & "/" & Mid(A, 3, 2) & "/" & Right(A, 4)
  ElseIf Len(TextBox1.Text) = 6 And InStr("/", A) = 0 Then                                    'Assumes two digit year
    TextBox1.Text = Left(A, 2) & "/" & Mid(A, 3, 2) & "/" & "20" & Right(A, 2)
  Else
    MsgBox "The format for the date must be either mm/dd/yyyy or mmddyyyy; please try again"
    Cancel = True
  End If
 
 
 End Sub
 
Last edited:
Upvote 0

Forum statistics

Threads
1,224,823
Messages
6,181,178
Members
453,021
Latest member
Justyna P

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top