我有一个.xlsm文件,我想在打开它时自动运行宏。当前文件在保存之前和关闭之前将文件以.xls文件保存在具有不同名称的其他位置。然而,在关闭之前给我错误,宏的自动运行也是如此。这是我的代码。
Private Sub Workbook_Open()
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Application.ScreenUpdating = False
Application.DisplayAlerts = False ' so you can overwrite without warning
ActiveWorkbook.SaveCopyAs "C:\Users\name\Desktop\testing.xls"
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Application.ScreenUpdating = False
Application.DisplayAlerts = False ' so you can overwrite without warning
ActiveWorkbook.SaveCopyAs "C:\Users\name\Desktop\testing.xls"
Application.DisplayAlerts = True
Application.ScreenUpdating = True
ActiveWorkbook.save
End Sub
End Sub
答案 0 :(得分:0)
对于初学者来说,你不能在其他事件中有事件。你的Workbook_BeforeSave
里面有Workbook_BeforeClose
和Workbook_Open
...这不行,无论如何我不确定它会是什么意思!
Private Sub Workbook_Open()
' This won't work:
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
'...
End Sub
Private Sub Workbook_BeforeClose(Cancel As Boolean)
'...
End Sub
End Sub
您需要单独设置活动,如下所示:
Private Sub Workbook_Open()
'Stuff to do when file opens...
End Sub
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
'Stuff to do before user saves the file...
End Sub
Private Sub Workbook_BeforeClose(Cancel As Boolean)
'Stuff to do before the user closes the file...
End Sub
此外,请考虑使用ActiveWorkbook
(或Me
)来避免任何歧义,而不是ThisWorkbook
。