【问题标题】:Change date's format after loading it to UserForm textbox将日期加载到用户窗体文本框后更改日期格式
【发布时间】:2014-02-27 14:28:51
【问题描述】:

我有一个带有文本框的用户表单。初始化文本框时,它会充满实际日期。我想要做的是用自定义日期格式填充它=DD-MM-YYYY

我在下面写了代码,但我不知道哪里出了问题。代码在插入值之前有 msgbox,MsgBox 以自定义格式显示日期,但当它传递给 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

【问题讨论】:

  • 试试这个:textbox.Value = Format(year_control, "dd-mm-yyyy") 或只是textbox.Value = Format(Date, "dd-mm-yyyy")
  • 既然year_control被格式化了,不应该保存为格式化日期吗?
  • 如果year_control 是字符串类型,那将是正确的,但它是日期。在线textbox.Value = year_control VBA 使用本地日期格式将year_control 转换为字符串
  • 如果我理解正确,那么我添加的 if 语句不应该正常工作,但确实如此。
  • rok 中有什么内容? - 来自这里year = Format(Date, "yyyy")rok_kontrola 是什么?

标签: vba date excel


【解决方案1】:

您不能“格式化”日期变量:

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

上面的代码什么也不做,因为 Date 变量只是简单地保存一个日期,更具体地说,VBA 将 Date 变量存储为 IEEE 64 位(8 字节)浮点数,表示从 100 年 1 月 1 日到 9999 年 12 月 31 日的日期和时间从 0:00:00 到 23:59:59。

无论您对这个变量做什么,它都会根据您的计算机识别的短日期格式显示日期。时间根据您的计算机识别的时间格式(12 小时制或 24 小时制)显示。

因此,虽然您可以更改 Date 变量所保存的内部值,但您不能将其格式存储在同一个变量中。

但是,您可以在字符串变量中随意显示它。所以,如果你使用:

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() 函数将返回一个变量(字符串),其中包含一个根据格式表达式中包含的指令格式化的表达式。

作为旁注,您可能还希望使用

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

因为它会更快,您也可以使用FormatDateTime 以其他各种方式格式化您的日期。

【讨论】:

  • 我现在明白了,simoco 给了我解决方案,但你也给了我一个解释。谢谢。
猜你喜欢
  • 1970-01-01
  • 2017-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多