【问题标题】:Userform text Box - UK Date Format用户表单文本框 - 英国日期格式
【发布时间】:2020-05-08 15:40:59
【问题描述】:

晚上

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

我正在尝试的一切都失败了,任何帮助都会得到很大的帮助。

非常感谢。

【问题讨论】:

    标签: excel vba date textbox userform


    【解决方案1】:

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

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

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

    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
    

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

    希望这会有所帮助!

    【讨论】:

    • 使用用户表单链接到电子表格 - Spreadsheet
    • 虽然我已经按照示例进行操作,但区域设置是英国,但是当将值写回电子表格时,它会将其转换回美国日期格式。
    猜你喜欢
    • 2019-08-26
    • 2016-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多