Mat*_*ten 1 excel vba excel-vba
我遇到了一个excel宏(VBA)的问题,该宏用于从excel电子表格中获取日期,减去一个月并将其重新格式化为MMM-YY.基本上我想采取3/31/2013并将其转换为2月13日
这是我的代码:
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
Run Code Online (Sandbox Code Playgroud)
我得到的结果是2/31/2013-13
所以我尝试更改prevMonth变量:
prevMonth = Format((Month(ReportDate) - 1) & "/" & Day(ReportDate) & "/" & Year(ReportDate), "mmm-yy")
Run Code Online (Sandbox Code Playgroud)
但是再次获得2013年2月31日
我试图将prevMonth声明为整数或日期但我得到类型不匹配错误.我只能将它声明为String但它仍然无法帮助程序.
在此先感谢您的帮助.
试试这个
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
Run Code Online (Sandbox Code Playgroud)