在VBA的文本框格式化MM / DD / YYYY日期 [英] Formatting MM/DD/YYYY dates in textbox in VBA
问题描述
我正在寻找一种将VBA文本框中的日期格式自动格式化为MM / DD / YYYY格式的方法,我希望它在用户键入时格式化。例如,一旦用户键入在第二个数字中,程序将自动输入/。现在,我使用以下代码获得了这个工作(以及第二个破折号):
Private Sub txtBoxBDayHim_Change()
如果txtBoxBDayHim.TextLength = 2或txtBoxBDayHim.TextLength = 5然后
txtBoxBDayHim.Text = txtBoxBDayHim.Text +/
End Sub
现在,这在打字时效果很好。然而,当尝试删除时,它仍然输入破折号,所以用户不可能删除过去的一个破折号(删除破折号的结果长度为2或5,然后再次运行该子,再加入另一个冲刺)。任何关于更好的方法的建议?
我从来没有建议使用文本框或输入框来接受日期。这么多事情可能会出错。我甚至不建议使用日历控件或日期选择器,因为您需要注册mscal.ocx或mscomct2.ocx,这是非常痛苦的,因为它们不是可自由分发的文件。
这是我推荐的。您可以使用此自定义日历来接受用户的日期
PROS :
<您不必担心用户输入错误信息
CONS :
Ummm ...嗯...不能想到任何...
如何使用
- 下载
Userform1.frm
和Userform1.frx
从这里。 - 在您的VBA中,只需导入
Userform1.frm
如ima所示
导入表单
运行
您可以在任何程序中调用它。例如
Sub Sample()
UserForm1.Show
End Sub
在行动中屏幕截图
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?
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:
- You don't have to worry about user inputting wrong info
- You don't have to worry user pasting in the textbox
- You don't have to worry about writing any major code
- Attractive GUI
- Can be easily incorporated in your application
- 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
- Download the
Userform1.frm
andUserform1.frx
from here. - In your VBA, simply import
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
这篇关于在VBA的文本框格式化MM / DD / YYYY日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!