2014-05-05 264 views
-2

我有一個.xlsm文件,我想在運行宏時自動打開它。在保存之前和關閉之前,當前文件將文件保存爲.xls在具有不同名稱的不同位置。然而,在關閉之前給我錯誤,宏自動運行也是如此。這是我的代碼。自動打開excel vba宏,beforeclose和beforesave

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

您是否嘗試用'ThisWorkbook'替換'ActiveWorkbook'? – PatricK

+0

只是爲了確認你的代碼是在** ThisWorkbook **而不是**模塊**中? – PatricK

+0

什麼錯誤?錯誤信息是什麼意思?你是怎麼試圖解決它告訴你錯的? –

回答

0

對於初學者,您不能在其他事件中發生類似事件。你有一個Workbook_BeforeSaveWorkbook_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),以避免任何含糊之處。