vbaoutlook

Sub Application_Quit() clears the value of defined variable


I'm trying to pop up a message box when Outlook is closed that tells what time Outlook was opened and what time it was closed.

Private startTime As String
Private endTime As String

Private Sub Application_Startup()
    startTime = CStr(TimeValue(Now))
End Sub

Private Sub Application_Quit()
    endTime = CStr(TimeValue(Now))

    MsgBox _
        "Session started at " + startTime + vbNewLine + _
        "Session ended at " + endTime, _
        vbOkOnly + vbInformation, _
        "Session Information"
End Sub

This is what I expect:
Expected result

My variables are cleared when Application_Quit() is triggered.
I receive this message box instead:
Actual result

I know that startTime is being given a value on Application_Startup(). When I add the following line of code to the end of Application_Startup() I receive the below message box.

    MsgBox _
        "Session started at " + startTime, _
        vbOkOnly + vbInformation, _
        "Session Information"

Debug message box

Why does Application_Quit() force startTime = "", and is there any way around it?


Solution

  • Using FSO to create a temporary text file removes the need for Global variables startTime and endTime as their values are stored in the temporary file and recalled during Application_Quit().

    Private FSO As Object
    Private oFile As Object
    
    Private Sub Application_Startup()
        Set FSO = CreateObject("Scripting.FileSystemObject")
        Set oFile = FSO.CreateTextFile("C:\Users\username\Documents\Outlook Files\temp.txt")
    
        oFile.WriteLine "Session started at " + CStr(TimeValue(Now))
        oFile.Close
    
        Set oFile = Nothing
        Set FSO = Nothing
    End Sub
    
    Private Sub Application_Quit()
        Set FSO = CreateObject("Scripting.FileSystemObject")
        Set oFile = FSO.OpenTextFile("C:\Users\username\Documents\Outlook Files\temp.txt")
    
        MsgBox _
            oFile.readline + vbNewLine + _
            "Session ended at " + CStr(TimeValue(Now)), _
            vbOKOnly + vbInformation, _
            "Session Information"
    
        oFile.Close
        Set oFile = Nothing
        FSO.DeleteFile ("C:\Users\username\Documents\Outlook Files\temp.txt")
        Set FSO = Nothing
    End Sub