Thursday, April 6, 2023

VBA code to close and re-open an Excel Workbook.

 It is possible to have VBA close and reopen a workbook by using the 'Application.OnTime' function to schedule a procedure to be run at a specified time in the future (either at a specific time of day or after a specific amount of time has passed).

  1. The first thing you need to do is determine which procedure to run.  In this example I created the Workbook_Activate sub in ThisWorkBook
    Private Sub Workbook_Activate()
        'There is nothing here
    End Sub

  2. Then I added the a module to reopen the Worksheet after a 3 second delay.
    Sub Worksheet_Reopen()
        Dim Wb As Excel.Workbook
        Set Wb = ThisWorkbook
        
        Dim WbPath As String
        WbPath = Wb.FullName
        
        Application.OnTime (Now + TimeValue("00:00:03")), WbPath & _
            "!ThisWorkbook.Workbook_Activate"

        Wb.Close (True)
    End Sub
     
    *It is important to note that this Worksheet must be saved before running Worksheet_Reopen or getting WbPath will fail.