加载到UserForm文本框后更改date的格式

我有一个带有文本框的用户窗体。 当文本框被初始化时,它会被填充实际的date。 我想要做的是填写自定义date格式= DD-MM-YYYY

我写了下面的代码,有什么不对,但我不知道什么是错的。 代码在插入值之前有msgbox, MsgBox以自定义格式显示date,但是当它传递给textbox.value它就像M/DD/YYY

 Dim year As Long, year_control As Date year = Format(Date, "yyyy") year_control = Format(Date, "dd-mm-yyyy") MsgBox (year_control) textbox.Value = year_control 

(……)

 If year_control < "01-04-" & year Then Me.Controls("rok1").Value = True Else Me.Controls("rok2").Value = True End If 

您不能“格式化”datevariables:

 year_control As Date year_control = Format(Date, "dd-mm-yyyy") 

上面的代码什么都不做,因为Datevariables只是简单地logging一个date,而VBA将Datevariables存储为IEEE 64位(8字节)的浮点数,表示date范围从1月1日到9999年12月31日,以及从0 :00:00至23:59:59

不pipe你对这个variables做什么,它总会根据你计算机识别的短date格式显示date。 时间根据计算机识别的时间格式(12小时或24小时)显示。

因此,尽pipe您可以更改Datevariables所拥有的内部值,但不能将其格式存储在相同的可放大的内部。

但是,你可以显示它,但是你想在一个stringvariables里面。 所以,如果你使用:

 Dim year As Long, year_control As Date Dim strYear_control As string year = Format(Date, "yyyy") year_control = Format(Date, "dd-mm-yyyy") strYear_control = Format(year_control , "dd-mm-yyyy") MsgBox (strYear_control) textbox.Value = strYear_control 

它应该像你期待的那样工作。 由于Format()函数将返回一个Variant(String),其中包含根据格式expression式中包含的指令格式化的expression式。

作为一个便笺,你也可以使用

 Format$(year_control , "dd-mm-yyyy") 

因为它会快得多,您还可以使用FormatDateTime以其他各种方式格式化date。