【问题标题】:How to control when a VBA Class Terminates如何控制 VBA 类何时终止
【发布时间】:2018-05-12 08:19:54
【问题描述】:

我编写了一个 VBA 类模块来从我的 Excel 工作簿创建 Outlook Mailitem 并监视 MailItem_Send 事件以在发送 Mailitem 后在我的工作簿中运行宏。

类模块如下所示:

Option Explicit

Public MailSubject As String
Public MailRecipient As String
Public MailBody As String

Public WithEvents mOutlook As Outlook.Application
Public WithEvents mMailItem As Outlook.MailItem

Private Sub Class_Initialize()
    Set mOutlook = New Outlook.Application
    MsgBox "mMailItem Class-object has been initialized"
End Sub

Public Sub CreateAndDisplayMailItem()

    Set mMailItem = Outlook.CreateItem(olMailItem)
    With mMailItem
        .To = MailRecipient
        .Subject = MailSubject
        .Body = MailBody
        .Display
    End With

End Sub

Private Sub Class_Terminate()
    Set mMailItem = Nothing
    MsgBox "mMailItem Class-object has ben terminated"
End Sub

Private Sub mOutlook_ItemSend(ByVal Item As Object, Cancel As Boolean)
    MsgBox "mOutlook Item Send Event has ben triggered"
    'Call MyMacro
End Sub
  • 使用上面显示的类模块从 Excel 工作簿中创建 Outlook Mailitem 后,Outlook Send-A-Mail 窗口会正确打开。

  • 如果我一直停留在 Send-A-Mail 窗口(不切换到任何其他窗口)直到邮件发送;我的 ItemSend 事件正确触发。

问题是:

  • 如果我返回我的 Excel 工作簿(因此我将窗口从显示的 MailItem 更改回我的工作簿),类对象在我的 MailItem 发送之前终止。

我的 MailItem 中的 Class_Terminate 事件应该在 MailItem 发送后触发!不是以前。

这里使用了这个类:

Sub Mail_Test()

Dim myMailItem As clsMailItem

Set myMailItem = New clsMailItem
myMailItem.MailSubject = "Test überschrift"
myMailItem.MailBody = "Test Body"
myMailItem.MailRecipient = "xyz@test.de"

myMailItem.CreateAndDisplayMailItem

End Sub

【问题讨论】:

  • 取决于类的初始化方式以及类对象的存储位置(在什么范围内)。所以请显示使用该类的代码。
  • 您可能需要在模块级别拥有类的变量
  • Dim myMailItem As clsMailItem 必须在Sub 之外。然后它在全局范围内,而不是在Sub 的范围内。如果在Sub的作用域内,则在Sub结束时终止。
  • @Storax 是的,我犯了一个小错误。我在 sub 本身中写了“Dim myMailItem As clsMailItem”。不在模块级别。非常感谢你。问题解决了:)
  • @AxelRichter 非常感谢! :) 现在我也确实不明白为什么我的代码不起作用并为未来学习。感谢您的帮助

标签: excel vba outlook


【解决方案1】:

如果我将你的班级命名为ol,这对我有用

Option Explicit

Dim xOl As New ol

Sub test()

    xOl.MailRecipient = "xyz@abc.com"
    xOl.MailBody = "Test"
    xOl.MailSubject = "Subject"
    xOl.CreateAndDisplayMailItem

End Sub

如果您在 sub 中声明 xOl,它将在 sub 结束时终止。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-27
    • 2019-09-01
    • 1970-01-01
    相关资源
    最近更新 更多