VBA Excel action when closing workbook

纵饮孤独 提交于 2020-01-03 17:48:54

问题


Is is possible automatically let Excel do an action when someone closes the file?

I'm pretty new to VBA an stackoverflow, so please have mercy..

Situation: I have an Excel file which is also used bij several other people. This file publishes a mhtml file whens saving. This mhtml file will be saved with the date of yesterday like "Dashboard 2015-01-12". The seen data in the mhtml file has to contain the date related to the file name. The data seen depends on a single cell in this excel file, G2

I want the Excel file to do this: change a single cell (G2) into the date of yesterday. Then save it. Then close it

I want this action to be done: when someone is closing the file

Code is have yet:

Sub sbWriteCellWhenClosing()

Workbooks("BOOK1.XLS").Close SaveChanges:=True
Range("G2") = Format(Now - 2, dd - mm - yy)

End Sub

Edit:

Will this do the job?

Private Sub Workbook_BeforeClose(Cancel As Boolean)
  Range("G2") = Format(Now - 1, dd - mm - yy)
   ActiveWorkbook.Close SaveChanges:=True
End Sub

回答1:


This is using the Workbook code:

Option Explicit

Private Sub Workbook_BeforeClose(Cancel As Boolean)
    Call sbWriteCellWhenClosing
End Sub

In a separate Module:

Sub sbWriteCellWhenClosing()

    ActiveSheet.Range("G2") = Format(Now - 1, "dd-mm-yy")   '-1 for yesterday
    ActiveWorkbook.Save

End Sub



回答2:


You should use Workbook.BeforeClose event : http://msdn.microsoft.com/en-us/library/office/ff194765%28v=office.15%29.aspx

to do that in project window in VBA editor you have to use ThisWorkbook and place your code there. Your code will work only for workbooks modified in this way.



来源:https://stackoverflow.com/questions/27923460/vba-excel-action-when-closing-workbook

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!