首页 > 解决方案 > 保存并关闭 2016 年生成的 Excel 文件,现在它在 Excel 365 上运行

问题描述

我的 VBA 多次保存和关闭文件时遇到问题,它有时有效,有时无效。我使用任务计划程序打开文件并等到 30 分钟关闭并保存文件。有时它要求我调试代码行

If wb.Name = GlobalBook.Name Then

如果我必须更新任何内容以使其正常工作,请告诉我。谢谢你。

模块 1 代码:

'Global variables
Public RunWhen As Double
Public Const cRunIntervalSeconds = 1800 ' seconds (set to 30 minutes)
Public Const cRunWhat = "SaveClose"  ' the name of the procedure to run
Public GlobalBook As Workbook

'Start Timer using interval set in global variables
Sub StartTimer()
    Set GlobalBook = ActiveWorkbook
    RunWhen = Now + TimeSerial(0, 0, cRunIntervalSeconds)
    Application.OnTime EarliestTime:=RunWhen, Procedure:=cRunWhat, _
        Schedule:=True
End Sub

'Stop the Timer whenever the workbook is closed prematurely
Public Sub StopTimer()
    On Error Resume Next
    Application.OnTime EarliestTime:=RunWhen, Procedure:=cRunWhat, _
        Schedule:=False
End Sub

'Close the workbook automatically once the Timer has expired
Public Sub SaveClose()
    'Time is up, workbook will save and close automatically
    Dim wb As Workbook
    For Each wb In Workbooks
        'Check to see if workbook is still open
        If wb.Name = GlobalBook.Name Then
            Set wb = Application.Workbooks(GlobalBook.Name)
            'Close workbook and Save Changes
            wb.Close SaveChanges:=True
        End If
        Next
End Sub

本工作簿代码:

'When the workbook is opened, call StartTimer()
Public Sub Workbook_Open()
    Run "StartTimer"
End Sub

'Detect if the workbook is closed
Public Sub Workbook_BeforeClose(Cancel As Boolean)
    'Cancel Saveclose
    Run "StopTimer"
End Sub

标签: excelvba

解决方案


推荐阅读