[英]Why is Excel VBA changing the year of my date when I format it?
我正在尝试将日期变量格式化为"mmm-yy,"
,但当日期为2016年时,格式化发生后,日期更改为2015年。这是我的代码:
(结果是输入框的字符串结果,该框要求用户以mmm-yy
格式输入日期,并且在此代码之前进行了测试,以确保第四个字符是连字符。
其他验证测试在此代码之后进行,因为我发现该字符串必须格式化为日期才能生效。)
result2 = result
result2 = Format(result2, "mmm-yy")
有什么建议么?
如果打算将输入框产生的值设置为等于类型为date的变量的值,则让用户输入程序所理解的日期(例如mm / dd / yyyy)。
如果由于某种原因用户必须以“ mmm-yy”格式输入日期,则将输入设置为等于字符串变量的值,然后使用[Month *] = Left([result],3)解构该变量。并且[Year] =“ 20”&right([result],2)。 然后,您必须构建日期,以便可以将其设置为date类型的新变量以放入Format函数中。
*当然,您必须具有一些键才能将“ Jan”,“ Feb”,“ Mar”等转换为值01、02、03等。
下面为我正确测试了:
公开子UserDateEntry()
Dim strUserEntry As String
Dim intMonth As Integer, intYear As Integer
strUserEntry = InputBox("Enter month & year in ""mmm-yy"" format.", "Date Entry", "Sep-16")
intMonth = Month(DateValue("01 " & Left(strUserEntry, 3) & " 2012"))
intYear = 20 & Right(strUserEntry, 2)
Application.Range("DateLoc").Value = Format(intMonth & " 01 " & intYear, "mm/dd/yyyy")
结束子
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.