我在 Outlook VBA 编程方面遇到了一个小问题,想知道是否有解决方案,或者这只是另一个“已知问题”。
上下文:
我已配置 Outlook 电子邮件帐户以通过 IMAP 访问我的网络电子邮件提供商。在 Outlook 中,我可以正确查看我的网络电子邮件文件夹。我的提供商的垃圾邮件过滤器将垃圾邮件移入垃圾邮件文件夹。
我想自动将放入垃圾邮件文件夹的邮件移动到我本地 pst 文件中的另一个文件夹中。
我让它工作了 99%(通过下面提供的代码供参考)。
问题:
我可以看到垃圾邮件文件夹中有邮件(文件夹名称旁边有一个粗体的未读邮件计数),但 ItemAdd 甚至只会在我单击文件夹时触发。那时,我看到了垃圾邮件文件夹的内容,然后看到所有新的垃圾邮件都被移到了我的本地文件夹中。
除了 ItemAdd 之外,是否还有另一个触发源可以用来运行我的代码而无需单击文件夹?当文件夹的未读计数发生变化时是否会触发事件?
技术细节:
- 视窗 8 操作系统
- 使用 Outlook 2002(是的,我知道...)
- 我是一位经验丰富的 C/C++ 开发人员,但在 VBA 方面的经验很少,而且在 Outlook 方面没有经验。
VBA代码:
Public WithEvents myItems As Outlook.Items
Public Sub Application_Startup()
Dim myNameSpace As Outlook.NameSpace
Const mailboxName As String = "Mail.com"
Const subfolderName As String = "Spam"
' Reference the items in the MAPI spam folder
' Because myOlItems is declared "WithEvents" the ItemAdd event will fire below.
Set myNameSpace = Application.GetNamespace("MAPI")
On Error GoTo noSpamFolder
Set myItems = myNameSpace.Folders(mailboxName).Folders(subfolderName).Items
On Error GoTo 0
Exit Sub
noSpamFolder:
MsgBox "Unable to find folder <" & mailboxName & "/" & subfolderName & ">"
End Sub
Private Sub myItems_ItemAdd(ByVal Item As Object)
Dim suspectFolder As Outlook.MAPIFolder
' Check to make sure it is an Outlook mail message, otherwise
' subsequent code will probably fail depending on what type
' of item it is.
If TypeName(Item) = "MailItem" Then
' Move message to the 'suspect' folder
On Error GoTo noSuspectFolder
Set suspectFolder = Outlook.Session.GetDefaultFolder(olFolderInbox).Folders("suspect")
On Error GoTo 0
Item.Move suspectFolder
End If
Exit Sub
noSuspectFolder:
MsgBox "Unable to find folder <suspect> as a sub-folder of default inbox folder"
End Sub