Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting MM/DD/YYYY dates in textbox in VBA

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?

like image 201
nobillygreen Avatar asked Aug 17 '12 19:08

nobillygreen


People also ask

How do you show mm/dd/yyyy in Userform textbox in Excel?

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.

How do you specify date format in VBA?

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.


1 Answers

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:

  1. You don't have to worry about user inputting wrong info
  2. You don't have to worry user pasting in the textbox
  3. You don't have to worry about writing any major code
  4. Attractive GUI
  5. Can be easily incorporated in your application
  6. Doesn't use any controls for which you need to reference any libraries like mscal.ocx or mscomct2.ocx

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)

  1. Download the Userform1.frm and Userform1.frx from here.
  2. In your VBA, simply import Userform1.frm as shown in the image below.

Importing the form

enter image description here

RUNNING IT

You can call it in any procedure. For example

Sub Sample()     UserForm1.Show End Sub 

SCREEN SHOTS IN ACTION

enter image description here

NOTE: You may also want to see Taking Calendar to new level

like image 108
Siddharth Rout Avatar answered Sep 18 '22 16:09

Siddharth Rout