在 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 + "/"结束子
现在,这在打字时效果很好.但是,当尝试删除时,它仍然进入破折号,因此用户不可能删除其中一个破折号(删除破折号的长度为 2 或 5,然后再次运行子程序,添加另一个破折号).关于更好的方法有什么建议吗?
我从不建议使用文本框或输入框来接受日期.很多事情都可能出错.我什至不建议使用日历控件或日期选择器,因为您需要注册 mscal.ocx 或 mscomct2.ocx,这非常痛苦,因为它们不是可自由分发的文件.
这是我推荐的.您可以使用此自定义日历来接受来自用户的日期
优点:
- 您不必担心用户输入错误信息
- 您不必担心用户在文本框中粘贴
- 您不必担心编写任何主要代码
- 有吸引力的图形用户界面
- 可以轻松地合并到您的应用程序中
- 不使用任何需要引用任何库(如 mscal.ocx 或 mscomct2.ocx)的控件
缺点:
嗯...嗯...想不出任何...
如何使用它(我的保管箱中缺少文件.日历的升级版本请参阅帖子底部)
- 从
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 (File missing from my dropbox. Please refer to the bottom of the post for an upgraded version of the calendar)
- 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
NOTE: You may also want to see Taking Calendar to new level
这篇关于在 VBA 中的文本框中格式化 MM/DD/YYYY 日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!