GD 阿诺德,
您确实可以按照@Brett 的回答使用ItemAdd 选项。
我使用类似的过程来自动上传收到的数据(作为电子邮件中的附件)并将其上传到 MySQL 数据库。该操作由 ItemAdd 方法触发,并逐一检查邮件。
简化说明:
在您的 VBA 代码中添加一个名为“EventClassModule”的类
在你的班级中,输入
Public WithEvents dItems As Outlook.Items
在您的 ThisOutlookSession 中创建一个注册 event_handler 的子程序:
Sub Register_Event_Handler()
Set myClass.dItems = Outlook.Items
End Sub
在您的 ThisOutlookSession 中创建一个处理 ItemAdd 事件的子程序,如下所示:
Private Sub dItems_ItemAdd(ByVal newItem As Object)
On Error GoTo ErrorHandler
Dim msg As Outlook.MailItem
If newItem.Class = olMail Then
Set msg = newItem
'Do something with the msg item, check rules, check subject, check whatever
'This will process messages when the arrive in your mailbox one by one.
End If
ProgramExit:
Exit Sub
ErrorHandler:
MsgBox Err.Number & " - " & Err.Description
Resume ProgramExit
End Sub
这些步骤应该为您提供一个在新邮件到达时触发的 sub。
然后您可以调用如下所示的函数/子。
下面的子程序基于可选的ruleSet 变量运行所有规则,它根据规则集检查rule.Name,如果ruleSet 字符串存在于rule.Name 中,那么它会执行一些代码。这样,您可以拥有多个规则,并且仅根据它们所属的“规则集”执行其中一些规则。你可以通过改变他们的名字来定义它。
这是对 Outlook 中“运行规则”选项的改进。
其中一些代码来自这里:Setting VBA to read personal inbox
Sub runRules(Optional ruleSet As String)
Dim olStore As Outlook.Store
Dim myRules As Outlook.Rules
Dim tmpInbox As Outlook.Folder
Dim tmpSent As Outlook.Folder
Dim rl As Outlook.Rule
'On Error Resume Next
'toTmpBox (ruleSet)
' get default store (where rules live)
Set olStore = Application.Session.DefaultStore
With olStore
Set tmpInbox = .GetDefaultFolder(olFolderInbox) '.Folders("tmpInbox")
Set tmpSent = .GetDefaultFolder(olFolderSentMail) '.Folders("tmpSentBox")
End With
' get rules
Set myRules = olStore.GetRules
' iterate through all the rules
For Each rl In myRules
Debug.Print rl.Conditions.Body.Enabled & " " & rl.Conditions.Body.Text
If InStr(LCase(rl.Name), ruleSet) > 0 And (rl.Enabled) Then
rl.Execute ShowProgress:=True, Folder:=tmpInbox
If ruleSet = "autorun" Then
rl.Execute ShowProgress:=True, Folder:=olStore.GetDefaultFolder(olFolderSentMail)
End If
ruleList = ruleList & vbCrLf & rl.Name
End If
Next
' tell the user what you did
ruleList = "These rules were executed " & _
vbCrLf & ruleList
MsgBox ruleList, vbInformation, "Macro: RunMyRules"
CleanUp:
Set olStore = Nothing
Set tmpInbox = Nothing
Set tmpSent = Nothing
Set rl = Nothing
Set myRules = Nothing
End Sub