用户窗体文本框 - 英国日期格式

Userform text Box - UK Date Format

晚上

我有一个用户表单,其中包含一些日期文本框。在电子表格中,日期格式是英国日期格式 (dd/mm/yyyy),当文本框调用电子表格中的信息时,它会将其转换为国际日期格式 (mm/dd/yyyy)。

我正在尝试的一切都失败了,我们将不胜感激。

非常感谢。

可能文本框使用美式 mm/dd/yyyy 格式设置日期格式,因为这是在您计算机的区域设置中定义的格式。更改此设置的一种简单方法是更改​​ 短日期 格式的区域设置。

但是,您可能希望与其他人共享此用户表单。并且不能保证他们的区域设置会以相同的方式配置。

因此,如果您的表单应始终使用英国格式,而不管用户的设置如何,那么您可以编写这样的格式化函数:

Public Function FormatDate(TheValue As Date) As String

    Dim dateSeparator As String
    dateSeparator = "/"

    FormatDate = Format(Day(TheValue), "00") & dateSeparator & _
        Format(Month(TheValue), "00") & dateSeparator & _
        Year(TheValue)

End Function

并像这样使用它:

MyUserForm.MyTextBox.Value = FormatDate(inputDateValue)

如果需要将此格式解析回日期,可以创建如下函数:

Public Function UKTextToDate(DateText As String) As Date

    Dim yearPart, monthPart, dayPart As String

    ' Remember that in VBA, String indexes are 1-based, not 0-based!
    ' UK format: dd/mm/yyyy - year starts at position 7 and runs for 4 characters
    yearPart = Mid(DateText, 7, 4)
    ' month starts at position 4 and runs for 2 characters
    monthPart = Mid(DateText, 4, 2)
    ' day starts at position 1 and runs for 2 characters
    dayPart = Left(DateText, 2)

    ' We should convert the text values back to integers, in order to use them
    ' in the DateSerial function.
    UKTextToDate = DateSerial(CInt(yearPart), CInt(monthPart), CInt(dayPart))

End Function

但是请注意,上面的代码不会检查无效输入。如果用户只能输入任何内容,您将需要编写一些代码来防止这种情况发生。

希望对您有所帮助!