Reputation: 3
I want to save an excel workbook at the end of the macro with a dynamic date in the file name. I want the name to contain the previous month. For instance, if the macro is run on 8/9/2013 I want the file to save with 7/2013 specified. This is what I have and it works great if I use the current month. But, if I ran this on 8/9/2013 I would want the file to save as "Monthly Report 2013-07".
ActiveWorkbook.SaveAs "\\FULL PATH\Monthly Report " & Format(Date, "yyyy-mm") & ".xls"
End Sub
I've also used something like this previously, but couldn't get this to subtract a month either:
wbNam = "Monthly Report_"
dt = Format(CStr(Now), "yyyy_mm")
ActiveWorkbook.SaveAs Filename:= wbNam & dt
End Sub
Thanks!
Upvotes: 0
Views: 10258
Reputation: 64
Just use this function
Public Function PreviousMonth(ByVal d As Date) As Date
PreviousMonth = DateSerial(Year(d), Month(d) - 1, Day(d))
End Function
DateSerial
is smart enough to support zero or negative month numbers.
In other words PreviousMonth(#1/1/2000#) is December 1st 1999.
Upvotes: 1