[英]VBA excel - How to 'saveas' file without preserving the first file
I have a workbook named sth_A where A is for today's date in dd-mm-yyyy format. 我有一本名为sth_A的工作簿,其中A以dd-mm-yyyy格式表示今天的日期。 Almost every day I open this workbook and make changes and then I update the file's name with today's date ( A ). 几乎每天我都会打开此工作簿并进行更改,然后使用今天的日期( A )更新文件名。
So I created a Workbook_BeforeClose
event with intention to write some code in it, that would rename my file automatically everytime I close the file. 因此,我创建了一个Workbook_BeforeClose
事件,打算在其中写入一些代码,该事件将在每次关闭文件时自动重命名文件。 I used Workbook.SaveAs
method, but this preserves the old file also. 我使用了Workbook.SaveAs
方法,但这也保留了旧文件。
Is there a way to rename an open file, or saveas without preserving the original, or another aproach that would do what I want in an elegant way? 有没有一种方法可以重命名打开的文件,另存为而不保存原始文件的另存为,或者可以优雅地完成我想要的操作的其他方法?
code: 码:
Private Sub Workbook_BeforeClose(Cancel As Boolean)
ThisWorkbook.SaveAs "sth" & Format(Date, "dd-mm-yyyy") & ".xlsm", FileFormat:=52, CreateBackup:=False
End Sub
also: 也:
Private Sub Workbook_BeforeClose(Cancel As Boolean)
ThisWorkbook.SaveAs ThisWorkbook.path & "/sth" & Format(Date, "dd-mm-yyyy") & ".xlsm", FileFormat:=52, CreateBackup:=False
End Sub
PS I want the first file deleted/overwriten in any case. PS我在任何情况下都希望删除/覆盖第一个文件。 Not only if it has the same name with the new one. 不仅具有与新名称相同的名称。
Save your workbook and Kill
the old one (basically what @Canute said). 保存您的工作簿并Kill
旧的工作簿(基本上是@Canute所说的)。
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Dim sOldName As String
sOldName = ThisWorkbook.FullName
ThisWorkbook.SaveAs ThisWorkbook.Path & Application.PathSeparator & _
"sth" & Format(Date, "dd-mm-yyyy") & ".xlsm", FileFormat:=52, CreateBackup:=False
Kill sOldName
End Sub
If you want to do this in the close workbook event then, 如果您想在关闭工作簿事件中执行此操作,
Hope this helps. 希望这可以帮助。
Add disable alert. 添加禁用警报。
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Application.DisplayAlerts = False
ThisWorkbook.SaveAs "sth" & Format(Date, "dd-mm-yyyy") & ".xlsm"
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.