Date Validation VBA

Noz2k

Well-known Member
Joined
Mar 15, 2011
Messages
693
Hey, I've only been using VBA for a couple of days and was wondering how to apply restrictions so that only data of a certain format can be entered into a textbox.

Specifically at the moment I am looking at making it so a textbox can only contain valid dates of the format "dd/mm/yyyy" and if this is not the case I would like a message box to come up as well as setting the focus back to that textbox.

I have tried

Code:
Private Sub Text1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
    If Text1.Value <> Format(CDate(Text1.Value), "dd/mm/yyyy") Then
 
        MsgBox "Must Be Format dd/mm/yyyy"
 
        Text1.SetFocus
 
    End If
End Sub
 

Excel Facts

Show numbers in thousands?
Use a custom number format of #,##0,K. Each comma after the final 0 will divide the displayed number by another thousand
Thanks, this works for the formatting. However it doesn't set the focus back into the textbox, so if you ignore the warning message then the invalid data stays.

Any idea on how to do this, or failing that clear the data entered?
 
Upvote 0
Hi,

Do you mean like this?

Code:
    If Text1.Value Like "##[/]##[/]####" Then
        MsgBox "yes"
    Else
        MsgBox "no"
        Text1.SetFocus
        Text1.Value = ""
    End If
 
Upvote 0
Yes, that's what I have tried, but the cursor still just moves to the next textbox rather than going back to textbox1

Here is my code

Code:
Private Sub Textbox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
    If Not Textbox1.Value Like "##[/]##[/]####" Then
        MsgBox "Must Be Format dd/mm/yyyy"
        Textbox1.SetFocus
        Textbox1.Value = ""
 
Else: Textbox2.SetFocus
 
End If
End Sub
 
Last edited:
Upvote 0
Don't worry, solved it, just needed to add

Code:
Cancel = True
after the SetFocus
 
Upvote 0

Forum statistics

Threads
1,224,521
Messages
6,179,289
Members
452,902
Latest member
Knuddeluff

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