Sub Application_Quit() 清除定义变量的值

问题描述 投票:0回答:1

我试图在 Outlook 关闭时弹出一个消息框,告知 Outlook 的打开时间和关闭时间。

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

这就是我所期望的:
Expected result

触发

Application_Quit()
时,我的变量将被清除。
我收到这个消息框:
Actual result

我知道 startTime 在 Application_Startup() 上被赋予了一个值。当我将以下代码行添加到 Application_Startup() 末尾时,我收到以下消息框。

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

Debug message box

为什么

Application_Quit()
会强迫
startTime = ""
,有什么办法可以解决吗?

vba outlook
1个回答
0
投票

使用 FSO 创建临时文本文件无需全局变量

startTime
endTime
,因为它们的值存储在临时文件中并在
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
© www.soinside.com 2019 - 2024. All rights reserved.