简体   繁体   English

Excel VBA-无法在用户窗体的文本框中更改日期格式的年份

[英]Excel VBA - Unable to change year in date format in TextBox in Userform

I have a userform with two TextBox fields for dates. 我有一个带两个文本框字段的日期用户窗体。 When I fill in the textboxes and press "tab" or click on the other box, the field will first fill in a cell on a worksheet and then format the date in the textbox (This allows for date entry in different formats such as 1/1/17, no matter what it should return as mmm dd, yyyy). 当我填写文本框并按“ Tab”或单击另一个框时,该字段将首先填写工作表上的单元格,然后在文本框中设置日期格式(这允许以其他格式输入日期,例如1 / 1/17,无论返回的内容是mmm dd,yyyy)。

Here's my issue. 这是我的问题。 Everything works absolutely perfectly, but the year is always stuck on 2017. I tried entering the date in all formats, the month and date change accordingly, but the year remains on 2017. 一切工作都非常完美,但年份始终停留在2017年。我尝试以所有格式输入日期,相应地更改了月份和日期,但年份仍然是2017年。

Here is the code below: 这是下面的代码:

Private Sub Button_OK_Click()

Sheets("Inputs").Range("C18").Value = Format(TextBox_StartDate.Value, "mmm dd, yyyy")
TextBox_StartDate.Value = Format(Sheets("Inputs").Range("C18").Text, "mmm dd, yyyy")
Sheets("Inputs").Range("C19").Value = Format(TextBox_EndDate.Value, "mmm dd, yyyy")
TextBox_EndDate.Value = Format(Sheets("Inputs").Range("C19").Text, "mmm dd, yyyy")
If TextBox_StartDate.Value = "" Or TextBox_EndDate.Value = "" Then
    MsgBox ("Start and End Dates must be filled in to continue.")
ElseIf Sheets("Inputs").Range("C18").Value > Sheets("Inputs").Range("C19").Value Then
    MsgBox ("End Date must be after Start Date.")
ElseIf Not (IsNumeric(Sheets("Inputs").Range("C18").Value) And IsNumeric(Sheets("Inputs").Range("C18").Value)) Then
    MsgBox ("Date fields must be filled in properly.")
Else
    Continue = True
    Unload Me
End If
End Sub

Private Sub TextBox_StartDate_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
If KeyCode = 9 Then
    Sheets("Inputs").Range("C18").Value = Format(TextBox_StartDate.Value, "mmm dd, yyyy")
     TextBox_StartDate.Value = Format(Sheets("Inputs").Range("C18").Text, "mmm dd, yyyy")
    Sheets("Inputs").Range("C19").Value = Format(TextBox_EndDate.Value, "mmm dd, yyyy")
     TextBox_EndDate.Value = Format(Sheets("Inputs").Range("C19").Text, "mmm dd, yyyy")
End If
End Sub

Any help would be much appreciated! 任何帮助将非常感激!

Sheets("Inputs").Range("C18").Value = Format(DateValue(TextBox_StartDate.Value), "mmm dd, yyyy")

I figured out the problem. 我解决了这个问题。 Cells C18 and C19 were formatted as dd-mmm. 单元格C18和C19的格式为dd-mm。 In order for the code to work properly, the year value must be included in the format. 为了使代码正常工作,格式中必须包含年份值。 Changing to format to dd-mmm-yy or mmm dd, yyyy in cells C18 and C19 fixed the problem for me. 在单元格C18和C19中将格式更改为dd-mmm-yy或mmm dd,yyyy对我来说解决了这个问题。

Thanks for the help! 谢谢您的帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM