在模块而不是Outlook VBA中的ThisOutlookSession中使用Application_MAPILogonComplete和WithEvents

时间:2018-08-10 16:18:59

标签: vba outlook ms-office outlook-vba outlook-2013

现在我所有的VBA代码都在ThisOutlookSession中。我想将所有内容都放入一个模块中,这样我就可以导出它,而其他人也可以导入它,而不必自己弄乱ThisOutlookSession。我希望对用户来说很容易-用户只需导入我的模块文件即可。

我的代码取决于Application_MAPILogonCompleteWithEvents。这些都不可用/无法在模块中工作。

我看到类具有Class_Initialize,但是它仅在初始化类对象时触发,因此我仍然需要某种Application_MAPILogonComplete事件。

反正有做我想做的事吗?将所有内容保存在可以导出和导入的模块或类中,该模块或类中的代码会在Outlook打开并支持WithEvents时运行,以便在将新电子邮件添加到文件夹时执行功能?

1 个答案:

答案 0 :(得分:0)

只有一个对象可以处理事件,因此您需要一个类-ThisOutlookSession是一个类,但是如果要模块化代码,则需要一个 class模块工作。

Option Explicit
Private WithEvents App As Outlook.Application

Private Sub Class_Initialize()
    Set App = Application
End Sub

Private Sub Class_Terminate()
    Set App = Nothing
End Sub

'select "App" from the left-hand dropdown at the top of the code pane.
'then select the event(s) you want to handle from the right-hand dropdown;
'the VBE will automatically generate the handler(s) with the correct signature.

剩下要做的就是拥有该类的实际实例(假设它称为Class1)-您将要在ThisOutlookSession中创建该实例

Option Explicit
Private AppEvents As Class1

Private Sub Application_Quit()
    Set AppEvents = Nothing
End Sub

Private Sub Application_Startup()
    Set AppEvents = New Class1
End Sub
相关问题