Excel VBA,如何制作仅文本框格式的日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43290152/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Excel VBA, How to make a TextBox format only Date
提问by Eka Oktavianus
I want to make a textbox but that text box only can be input by date format and nothing else.
我想制作一个文本框,但该文本框只能按日期格式输入,而不能按其他格式输入。
回答by YowE3K
As far as I know, you can't (easily) force the text in a TextBox to always be a valid date, but you can check what has been entered as the user tries to leave the TextBox:
据我所知,您不能(轻松)强制 TextBox 中的文本始终为有效日期,但您可以检查用户尝试离开 TextBox 时输入的内容:
Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
If Not IsDate(TextBox1.Text) Then
MsgBox "Date required"
Cancel = True
End If
'Display value in another textbox for testing purposes
TextBox2.Text = Format(CDate(TextBox1.Text), "dd/mm/yyyy")
End Sub
Using IsDate
will allow anysystem-recognised date to be entered, so you should use CDate(TextBox1.Text)
to access the date entered. Don't rely on the text itself being in a particular format because the text entered could be, for instance:
UsingIsDate
将允许输入任何系统识别的日期,因此您应该使用CDate(TextBox1.Text)
访问输入的日期。不要依赖文本本身的特定格式,因为输入的文本可能是,例如:
"08/03/2017"
"8 March 2017"
"8 Mar"
"8/3/17"
"08/03/2017"
"8 March 2017"
"8 Mar"
"8/3/17"