VBA 宏并将日期格式更改为 mmm-yy
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15843054/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VBA Macro and changing date format to mmm-yy
提问by Matthew Minten
I am having problems with an excel macro (VBA) that is meant to grab a date from an excel spreadsheet, subtract one month and reformat it to MMM-YY. Basically I want to take 3/31/2013 and convert it to Feb-13
我在使用 excel 宏 (VBA) 时遇到问题,该宏旨在从 excel 电子表格中获取日期,减去一个月并将其重新格式化为 MMM-YY。基本上我想把 2013 年 3 月 31 日转换为 2 月 13 日
Here is my code:
这是我的代码:
Dim ReportDate As Date
ReportDate = Worksheets("Current").Cells(2, 16) 'ex. 03-31-2013
prevMonth = Format((Month(ReportDate) - 1) & "/" & Day(ReportDate) & "/" & Year(ReportDate), "mmm") & "-" & Format(ReportDate, "yy")
Debug.Print prevMonth
The result I get is 2/31/2013-13
我得到的结果是 2/31/2013-13
So I tried changing the prevMonth variable:
所以我尝试改变 prevMonth 变量:
prevMonth = Format((Month(ReportDate) - 1) & "/" & Day(ReportDate) & "/" & Year(ReportDate), "mmm-yy")
But got just 2/31/2013 again
但再次获得了 2/31/2013
I tried to declare prevMonth as an Integer or a Date but I get a type mismatch error. I can only declare it as a String but it still doesn't help the program.
我试图将 prevMonth 声明为整数或日期,但出现类型不匹配错误。我只能将它声明为一个字符串,但它仍然对程序没有帮助。
Thanks in advance for your help.
在此先感谢您的帮助。
回答by chris neilsen
Try this
尝试这个
Sub Demo()
Dim ReportDate As Date
Dim prevMonth As Date
ReportDate = Worksheets("Current").Cells(2, 16) 'ex. 03-31-2013
prevMonth = DateAdd("m", -1, ReportDate)
Debug.Print Format(prevMonth, "mmm-yy")
End Sub