You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用VBA将Excel文件另存为含昨日日期的文件名

解决VBA宏保存文件时添加昨日日期的问题

核心需求

宏运行完成后,将文件保存至远程路径,文件名包含昨日日期。

修改后的完整代码

'Input Excel File's Full Path
ExcelFilePath = "C:\Abc.xls"

'Input Module/Macro name within the Excel File
MacroPath = "Module.MacroName"

'Create an instance of Excel
Set ExcelApp = CreateObject("Excel.Application")

'Do you want this Excel instance to be visible?
ExcelApp.Visible = False ' 直接写True或False,无需引号和or

'Prevent any App Launch Alerts (ie Update External Links)
ExcelApp.DisplayAlerts = False

'Open Excel File
Set wb = ExcelApp.Workbooks.Open(ExcelFilePath)

'Execute Macro Code
ExcelApp.Run MacroPath

'生成昨日日期字符串,格式为yyyy-mm-dd(避免文件名含非法字符)
Dim yesterdayDate As String
yesterdayDate = Format(DateAdd("d", -1, Date), "yyyy-mm-dd")

'Save Excel File with yesterday's date in filename
wb.SaveAs "\\XYZ\123\Abc_" & yesterdayDate & ".xls"

'Reset Display Alerts Before Closing
ExcelApp.DisplayAlerts = True

'Close Excel File
wb.Close

'End instance of Excel
ExcelApp.Quit

'Leaves an onscreen message!
MsgBox "Your Automated Task successfully ran at " & TimeValue(Now), vbInformation

关键修改说明

  • 生成昨日日期:用DateAdd("d", -1, Date)获取昨日日期,通过Format函数转换成yyyy-mm-dd格式(规避/等文件名非法字符,兼容性最优)。
  • 拼接文件名:将日期字符串与原文件名用下划线拼接,保证文件名清晰合规。
  • 修正Visible属性:原代码ExcelApp.Visible = "True" or "False"为错误写法,直接赋值True或False即可,无需引号。

内容的提问来源于stack exchange,提问作者Anonymous

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 16:15:49