我正在尝试将进入我的主收件箱(用于测试,未来的第二个收件箱)的电子邮件路由到子文件夹。我希望它在收到时的所有物品上激活。但是,在 VBA 代码的最后一行,
Item.Move olnamespace.Folders("My Name").Folders("Inbox").Folders("Subfolder")
失败并出现运行时错误 91。我不确定原因并尝试对其进行故障排除。 VBA - 更不用说 Outlook 方面 - 对我来说非常新。
Private WithEvents secondinboxitems As Outlook.Items
Sub initializesecondinboxitems()
Dim olapp As Outlook.Application
Dim olnamespace As Outlook.NameSpace
Dim secondinboxfolder As Outlook.Folder
'initialize outlook application and namespace
Set olapp = New Outlook.Application
Set olnamespace = olapp.GetNamespace("MAPI")
'specify the folder containing the emails in the second inbox
Set secondinboxfolder = olnamespace.Folders("My Name").Folders("Inbox")
'get the items collection for the second inbox folder
Set secondinboxitems = secondinboxfolder.Items
End Sub
Private Sub secondinboxitems_ItemAdd(ByVal Item As Object)
'code to process the items
Dim olapp As Outlook.Application
Dim olnamespace As Outlook.NameSpace
Dim keyword As String
'set the keywords to search for.
keyword = "Keyword"
'check if the received item is a mail item
If TypeOf Item Is Outlook.MailItem Then
'read email body as plain text
Dim body As String
body = Item.body
'check if keyword is present
If InStr(1, body, keyword, vbTextCompare) > 0 Then
'Dim itemtomove As Outlook.MailItem
'Set itemtomove = Item
Item.Move olnamespace.Folders("My Name").Folders("Inbox").Folders("Subfolder")
End If
End If
End Sub
这就是我正在处理的事情。我尝试更具体地将该项目分配为邮件项目。而且,我尝试重新设置
GetNamespace("MAPI")
。我认为两者都不是问题。我想当它没有解决问题时证实了这一点。任何有关子项目在 item.move 上失败的原因的指示将不胜感激。
还有!它似乎是根据文本比较的
debug.print
来阅读关键字的电子邮件。
该错误很可能不是由
MailItem.Move
引发的,而是由检索目标文件夹的代码引发的。尝试将该行分成两行,检查您是否确实无法检索目标文件夹
set targetFolder = olnamespace.Folders("My Name").Folders("Inbox").Folders("Subfolder")
Item.Move targetFolder
如果您正在处理默认收件箱文件夹的子文件夹,请使用 GetDefaultFolder:
set targetFolder = olapp.Session.GetDefaultFolder(olFolderInbox).Folders("Subfolder")