用于保存具有动态日期的工作表的 VBA

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18153767/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 22:40:49  来源:igfitidea点击:

VBA for saving worksheet with dynamic date

excel-vbavbaexcel

提问by Matt Puck

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".

我想在宏的末尾保存一个 Excel 工作簿,文件名中包含动态日期。我希望名称包含上个月。例如,如果宏在 8/9/2013 上运行,我希望文件以指定的 7/2013 保存。这就是我所拥有的,如果我使用当月,它会很好用。但是,如果我在 2013 年 8 月 9 日运行此程序,我希望将文件另存为“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!

谢谢!

回答by user2668920

Just use this function

只需使用此功能

Public Function PreviousMonth(ByVal d As Date) As Date
PreviousMonth = DateSerial(Year(d), Month(d) - 1, Day(d))
End Function

DateSerialis smart enough to support zero or negative month numbers. In other words PreviousMonth(#1/1/2000#) is December 1st 1999.

DateSerial足够聪明以支持零或负月份数。换句话说,PreviousMonth(#1/1/2000#) 是 1999 年 12 月 1 日。

回答by Joe

Try:

尝试:

dt = Format(DateAdd("m", -1, Now), "yyyy_mm")