用户表单日期格式文本框

时间:2019-04-04 21:18:53

标签: excel vba userform

因此,我使用的是excel用户窗体UserForm1,其中某些字段要求以YYYY/MM/DD格式输入日期。因此,我已将名为<{1>}的弹出式日历导入了CalenderForm的用户窗体,允许用户单击文本框,日历应在该字段旁边弹出。

我从以下网站获得日历:https://trevoreyre.com/portfolio/excel-datepicker/

我遇到的问题是将日期值从CalenderForm转换为YYYY / MM / DD日期格式的文本框字段。

以下是用户表格的图片: enter image description here

下面的代码用于会议前的文本框(已编辑)

Private Sub tbpremeeting_Change()
    Dim dateVariable As Date
    dateVariable = CalendarForm.GetDate
    Me.tbpremeeting.Text = Format(dateVariable, "yyyy/mm/dd")

End Sub

日历如下所示: enter image description here

1 个答案:

答案 0 :(得分:1)

您需要阅读CalendarForm.frm中的说明

当用户取消而不选择日期时,返回“ 1899/12/30”。

'   OkayButton (Boolean) - Controls whether or not the Okay button is visible. If the
'       Okay button is enabled, when the user selects a date, it is highlighted, but
'       is not returned until they click Okay. If the Okay button is disabled,
'       clicking a date will automatically return that date and unload the form.


'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    ' UserForm_QueryClose
    '
    ' I originally included this sub to override when the user cancelled the
    ' CalendarForm using the X button, in order to avoid receiving an invalid date value
    ' back from the userform (1/0/1900 12:00:00 AM). This sub sets DateOut to currently
    ' selected Date, or to the initial SelectedDate passed to the GetDate function if user
    ' has not changed the selection, or the Okay button is not enabled.
    '
    ' Note that it is still possible for the CalendarForm to return an invalid date value
    ' if no initial SelectedDate is set, the user does not make any selection, and then
    ' cancels the userform.
    '

        ' I ended up removing the sub, because I like being able to detect if the user has
        ' cancelled the userform by testing the date from it. For instance, if user selects
        ' a date, but then changes their mind and cancels the userform, you wouldn't want to
        ' still return that date to your variable. You would want to revert to their previous
        ' selection, or do some error handling, if necessary.
        '
        ' If you want the functionality described above, of returning the selected date or
        ' initial date if the user cancels, you can un-comment this sub.
        '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
        'Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
        '    If CloseMode = 0 Then
        '        Cancel = True
        '        DateOut = SelectedDateIn
        '        Me.Hide
        '    End If
        'End Sub