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 user types in the second number, the program will automatically type in a "/". Now, I got this working (as well as the second dash) with the following code:
Private Sub txtBoxBDayHim_Change() If txtBoxBDayHim.TextLength = 2 or txtBoxBDayHim.TextLength = 5 then txtBoxBDayHim.Text = txtBoxBDayHim.Text + "/" End Sub
Now, this works great when typing. However, when trying to delete, it still enters in the dashes, so its impossible for the user to delete past one of the dashes (deleting a dash results in a length of 2 or 5, and the sub is then run again, adding in another dash). Any suggestions on a better way to do this?
This is one I can answer. Firstly select the userform in question and select date field. Press F4 to show the properties for that field then scroll down to the field named text and input dd/mm/yyyy and this will mask the entry into the userform.
Click on Insert tab > select Module. Step 2: Write the subprocedure for VBA Format Date or choose anything to define the module. Step 3: Choose the range cell first as A1. Step 4: Then use the Number Format function as shown below.
I never suggest using Textboxes or Inputboxes to accept dates. So many things can go wrong. I cannot even suggest using the Calendar Control or the Date Picker as for that you need to register the mscal.ocx or mscomct2.ocx and that is very painful as they are not freely distributable files.
Here is what I recommend. You can use this custom made calendar to accept dates from the user
PROS:
CONS:
Ummm...Ummm... Can't think of any...
HOW TO USE IT (File missing from my dropbox. Please refer to the bottom of the post for an upgraded version of the calendar)
Userform1.frm
and Userform1.frx
from here.Userform1.frm
as shown in the image below.Importing the form
RUNNING IT
You can call it in any procedure. For example
Sub Sample() UserForm1.Show End Sub
SCREEN SHOTS IN ACTION
NOTE: You may also want to see Taking Calendar to new level
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With