在自动关闭工作簿之前保存文件

时间:2015-04-16 23:03:18

标签: excel vba excel-2007

如果工作簿处于非活动状态1分钟,我想关闭它。但在关闭之前,我想保存它的备份,但不要对原始版本进行任何更改。如何合并此代码:

ActiveWorkbook.SaveAs filename:=filename, FileFormat:=xlWorkbookNormal

进入此程序

Sub SetTimer()
    Dim bookname
    Dim filename
    DownTime = Now + TimeValue("00:01:00")
    bookname = ActiveWorkbook.Name
    filename = "C:\myhome\backups\" & bookname
    Application.OnTime EarliestTime:=DownTime, _
      Procedure:="ShutDown", Schedule:=True
End Sub

如果我将其插入代码中,它会在定时器完成之前要求我保存。我希望在时间结束后再询问。

2 个答案:

答案 0 :(得分:1)

只需将一个事件处理程序放入Workbook_BeforeClose即可。我亲自检查一下它是否也被改变了,所以你不会得到一堆不必要的备份:

Private Sub Workbook_BeforeClose(Cancel As Boolean)

    Application.DisplayAlerts = False
    If Not Me.Saved Then
        Me.SaveAs "C:\myhome\backups\" & Me.Name, xlWorkbookNormal
    End If
    Application.DisplayAlerts = True

End Sub

答案 1 :(得分:1)

我认为这就是你所追求的目标:

Public Sub SetTimer()
    Dim DownTime As Date
    DownTime = Now + TimeValue("00:01:00")

    Application.OnTime EarliestTime:=DownTime, _
      Procedure:="ShutDown", Schedule:=True
End Sub


Private Sub ShutDown()
    ' Be careful about using ActiveWorkbook vs ThisWorkbook vs getting a direct reference to the required workbook.
    Dim bookname As String
    bookname = ActiveWorkbook.Name

    Dim filename As String
    filename = "C:\myhome\backups\" & bookname

    ActiveWorkbook.SaveAs filename:=filename, FileFormat:=xlWorkbookNormal
End Sub

您需要将SaveAs放入一个名为" ShutDown"的单独方法中。我假设你把它放在原始方法的末尾。对Application.OnTime()的调用运行和调度ShutDown()稍后将被调用,然后立即继续运行SetTimer()中的其余代码。