A stripped down idea of what I'm trying to accomplish would be to have a message box popup when Outlook is closed that tells you what time Outlook was opened and what time it was closed. Here is the code I am using to try to accomplish this:
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 to get:
However, the issue I'm having is that my variables are cleared when Application_Quit() is triggered. I receive this message box instead:
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"
Why does Application_Quit()
force startTime = ""
, and is there any way around it?
Solved - Thanks to Adirmola - 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