title: Save and Close Excel file generated by 2016 and now it's running on Excel 365
body: <p>I've got problem with my VBA for Saving and Closing file so many times, it works sometimes and sometimes dont work. I use Task Scheduler for opening file and wait until 30 minutes to close and save file. Sometimes it asked me to debug the code on the line of</p>
  
  <pre><code>If wb.Name = GlobalBook.Name Then
  </code></pre>
  
  <p>Please let me if I had to update anything to make it work. Thank you.</p>
  
  <p>Module 1 Code:</p>
  
  <pre><code>'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
  </code></pre>
  
  <p>This Workbook Code: </p>
  
  <pre><code>'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
  </code></pre>