使用VBA创建Outlook文件夹和规则

huangapple go评论54阅读模式
英文:

Creating Outlook folders and rules using VBA

问题

我尝试为所选电子邮件的每个唯一发件人创建一个收件箱文件夹,以及一个将来将来自这些发件人的邮件移动到相应文件夹的规则。

Sub CreateSenderFolderAndRule()
    Dim objNS As Outlook.NameSpace
    Dim objInbox As Outlook.MAPIFolder
    Dim objMail As Outlook.MailItem
    Dim objSenderFolder As Outlook.MAPIFolder
    Dim strFolderName As String
    Dim objRules As Outlook.Rules
    Dim objRule As Outlook.Rule
    Dim objCondition As Outlook.RuleCondition
    Dim objAction As Outlook.RuleAction
    Dim objRuleExec As Object
    
    ' 获取收件箱的引用
    Set objNS = Application.GetNamespace("MAPI")
    Set objInbox = objNS.GetDefaultFolder(olFolderInbox)
    
    ' 检查是否有选定的项目
    If Application.ActiveExplorer.Selection.Count = 0 Then
        MsgBox "请选择要创建文件夹的邮件。"
        Exit Sub
    End If
    
    ' 获取选定的项目(应该是邮件项目)
    Set objMail = Application.ActiveExplorer.Selection.Item(1)
    
    ' 检查电子邮件的发件人是否已经有一个文件夹
    On Error Resume Next
    Set objSenderFolder = objInbox.Folders(objMail.SenderName)
    On Error GoTo 0
    
    ' 如果文件夹不存在,创建它
    If objSenderFolder Is Nothing Then
        ' 使用发件人的名称创建一个文件夹
        strFolderName = objMail.SenderName
        Set objSenderFolder = objInbox.Folders.Add(strFolderName, olFolderInbox)
    End If
    
    ' 创建一个规则,将来自发件人的新邮件移动到新文件夹
    Set objRules = Application.Session.DefaultStore.GetRules()
    
    ' 暂时禁用所有现有规则
    Dim objExistingRule As Outlook.Rule
    For Each objExistingRule In objRules
        objExistingRule.Enabled = False
    Next objExistingRule
    
    ' 创建新规则
    Set objRule = objRules.Create("移动邮件从 " & objMail.SenderName, olRuleReceive)
    Set objCondition = objRule.Conditions.SenderAddress
    With objCondition
        .Enabled = True
        .Address = objMail.SenderEmailAddress
    End With
    Set objAction = objRule.Actions.MoveToFolder
    With objAction
        .Enabled = True
        .ExecutionOrder = 1 ' 确保该规则在其他规则之前执行
        .Folder = objSenderFolder
    End With
    objRule.Enabled = True
    
    ' 重新启用现有规则
    For Each objExistingRule In objRules
        objExistingRule.Enabled = True
    Next objExistingRule
    
    ' 保存规则
    objRules.Save
    
    ' 调试代码,检查创建新规则后的规则
    Debug.Print "规则数量: " & objRules.Count
    For Each objExistingRule In objRules
        Debug.Print objExistingRule.Name & " - " & objExistingRule.Enabled
    Next objExistingRule
    
    ' 执行规则
    Set objRuleExec = Application.Session.DefaultStore.GetRules.ExecuteRule(objRule.Name)
    
    ' 成功消息
    MsgBox "已创建文件夹: " & objSenderFolder.Name & vbCrLf & "已创建规则: " & objRule.Name
End Sub

为所选邮件的发件人创建了一个新文件夹,但没有创建新规则,并且我没有收到成功消息。

我遇到了

运行时错误 '438: 对象不支持此属性或方法

在以下行:

Set objCondition = objRule.Conditions.SenderEmailAddress

我使用的是Outlook 365(版本2103)在Windows 10计算机上运行宏,从Outlook的VBA编辑器中运行。我尝试了对代码进行各种更改,包括不同的RuleCondition参数,更改FilterType属性以及使用不同的文件夹创建方法。

英文:

I am trying to create a folder in the Inbox for each unique sender of selected email(s), and a rule to move future messages from those senders to the appropriate folders.

Sub CreateSenderFolderAndRule()
    Dim objNS As Outlook.NameSpace
    Dim objInbox As Outlook.MAPIFolder
    Dim objMail As Outlook.MailItem
    Dim objSenderFolder As Outlook.MAPIFolder
    Dim strFolderName As String
    Dim objRules As Outlook.Rules
    Dim objRule As Outlook.Rule
    Dim objCondition As Outlook.RuleCondition
    Dim objAction As Outlook.RuleAction
    Dim objRuleExec As Object
    
    ' Get reference to the inbox
    Set objNS = Application.GetNamespace("MAPI")
    Set objInbox = objNS.GetDefaultFolder(olFolderInbox)
    
    ' Check if there is a selected item
    If Application.ActiveExplorer.Selection.Count = 0 Then
        MsgBox "Please select a message to create a folder for."
        Exit Sub
    End If
    
    ' Get the selected item (should be a mail item)
    Set objMail = Application.ActiveExplorer.Selection.Item(1)
    
    ' Check if the sender of the email is already a folder
    On Error Resume Next
    Set objSenderFolder = objInbox.Folders(objMail.SenderName)
    On Error GoTo 0
    
    ' If the folder does not exist, create it
    If objSenderFolder Is Nothing Then
        ' Create a folder with the name of the sender
        strFolderName = objMail.SenderName
        Set objSenderFolder = objInbox.Folders.Add(strFolderName, olFolderInbox)
    End If
    
    ' Create a rule to move new messages from the sender to the new folder
    Set objRules = Application.Session.DefaultStore.GetRules()
    
    ' Temporarily disable all existing rules
    Dim objExistingRule As Outlook.Rule
    For Each objExistingRule In objRules
        objExistingRule.Enabled = False
    Next objExistingRule
    
    ' Create the new rule
    Set objRule = objRules.Create("Move messages from " & objMail.SenderName, olRuleReceive)
    Set objCondition = objRule.Conditions.SenderAddress
    With objCondition
        .Enabled = True
        .Address = objMail.SenderEmailAddress
    End With
    Set objAction = objRule.Actions.MoveToFolder
    With objAction
        .Enabled = True
        .ExecutionOrder = 1 ' Ensure the rule is executed before other rules
        .Folder = objSenderFolder
    End With
    objRule.Enabled = True
    
    ' Re-enable the existing rules
    For Each objExistingRule In objRules
        objExistingRule.Enabled = True
    Next objExistingRule
    
    ' Save the rules
    objRules.Save
    
    ' Debugging code to check the rules after the new one has been created
    Debug.Print "Number of rules: " & objRules.Count
    For Each objExistingRule In objRules
        Debug.Print objExistingRule.Name & " - " & objExistingRule.Enabled
    Next objExistingRule
    
    ' Execute the rule
    Set objRuleExec = Application.Session.DefaultStore.GetRules.ExecuteRule(objRule.Name)
    
    ' Success message
    MsgBox "Created folder: " & objSenderFolder.Name & vbCrLf & "Created rule: " & objRule.Name
End Sub

A new folder is created for the sender of the selected email(s), but no new rule is created, and I don't get the success message.

I get

>Run-time error '438: Object doesn't support this property or method

on the line

Set objCondition = objRule.Conditions.SenderEmailAddress 

I'm using Outlook 365 (version 2103) on a Windows 10 machine, and running the macro from the VBA editor in Outlook.

I tried various changes to the code, including different RuleCondition parameters, changing the FilterType property, and using different folder creation methods.

答案1

得分: 2

在你完成后,将Rules对象存储在专用变量中,然后调用Rules.Save

set objRules = Application.Session.DefaultStore.GetRules()
Set objRule = objRules.Create("Move messages from " & objMail.SenderName, olRuleReceive)
...
objRules.Save
英文:

Store Rules object in a dedicated variable and call Rules.Save after you are done:

set objRules = Application.Session.DefaultStore.GetRules()
Set objRule = objRules.Create("Move messages from " & objMail.SenderName, olRuleReceive)
...
objRules.Save

答案2

得分: 0

启用规则后,还必须使用Rules.Save来保存规则,以便规则及其启用状态在当前会话之外持久存在。只有在成功保存后规则才会被启用。

请注意,保存不兼容规则或具有未正确定义操作或条件的规则将返回错误。

此外,在与Exchange服务器的慢速连接上,Rules.Save可能是一项性能昂贵的操作。有关使用进度对话框的更多信息,请参阅Outlook对象模型中的管理规则

例如,以下VBA宏将消息从特定发件人移动到特定文件夹,除非消息主题包含特定词汇:

Sub CreateRule() 
    Dim colRules As Outlook.Rules 
    Dim oRule As Outlook.Rule 
    Dim colRuleActions As Outlook.RuleActions 
    Dim oMoveRuleAction As Outlook.MoveOrCopyRuleAction 
    Dim oFromCondition As Outlook.ToOrFromRuleCondition 
    Dim oExceptSubject As Outlook.TextRuleCondition 
    Dim oInbox As Outlook.Folder 
    Dim oMoveTarget As Outlook.Folder 

    '指定规则移动操作的目标文件夹
    Set oInbox = Application.Session.GetDefaultFolder(olFolderInbox) 
    '假设目标文件夹已存在
    Set oMoveTarget = oInbox.Folders("Eugene") 

    '从Session.DefaultStore对象获取规则
    Set colRules = Application.Session.DefaultStore.GetRules() 

    '通过向规则集合添加接收规则来创建规则
    Set oRule = colRules.Create("Dan's rule", olRuleReceive) 

    '在ToOrFromRuleCondition对象中指定条件
    '条件是如果消息来自"Dan Wilson"
    Set oFromCondition = oRule.Conditions.From 
    With oFromCondition 
        .Enabled = True 
        .Recipients.Add ("Eugene Astafiev") 
        .Recipients.ResolveAll 
    End With 

    '在MoveOrCopyRuleAction对象中指定操作
    '操作是将消息移动到目标文件夹
    Set oMoveRuleAction = oRule.Actions.MoveToFolder 
    With oMoveRuleAction 
        .Enabled = True 
        .Folder = oMoveTarget 
    End With 

    '在TextRuleCondition对象中指定主题的异常条件
    '异常条件是如果主题包含"fun"或"chat"
    Set oExceptSubject = _
        oRule.Exceptions.Subject 
    With oExceptSubject 
        .Enabled = True 
        .Text = Array("fun", "chat") 
    End With 

    '更新服务器并显示进度对话框
    colRules.Save 
End Sub
英文:

After you enable a rule, you must also save the rule by using Rules.Save so that the rule and its enabled state will persist beyond the current session. A rule is only enabled after it has been saved successfully.

Be aware, saving rules that are incompatible or have improperly defined actions or conditions will return an error.

Also Rules.Save can be an expensive operation in terms of performance on slow connections to Exchange server. For more information on using the progress dialog box, see Manage Rules in the Outlook Object Model.

For example, the following VBA macro moves messages from a specific sender to a specific folder, unless the message contains certain terms in the subject:

Sub CreateRule() 
    Dim colRules As Outlook.Rules 
    Dim oRule As Outlook.Rule 
    Dim colRuleActions As Outlook.RuleActions 
    Dim oMoveRuleAction As Outlook.MoveOrCopyRuleAction 
    Dim oFromCondition As Outlook.ToOrFromRuleCondition 
    Dim oExceptSubject As Outlook.TextRuleCondition 
    Dim oInbox As Outlook.Folder 
    Dim oMoveTarget As Outlook.Folder 
 
    'Specify target folder for rule move action 
    Set oInbox = Application.Session.GetDefaultFolder(olFolderInbox) 
    'Assume that target folder already exists 
    Set oMoveTarget = oInbox.Folders("Eugene") 
     
    'Get Rules from Session.DefaultStore object 
    Set colRules = Application.Session.DefaultStore.GetRules() 
     
    'Create the rule by adding a Receive Rule to Rules collection 
    Set oRule = colRules.Create("Dan's rule", olRuleReceive) 
 
    'Specify the condition in a ToOrFromRuleCondition object 
    'Condition is if the message is from "Dan Wilson" 
    Set oFromCondition = oRule.Conditions.From 
    With oFromCondition 
        .Enabled = True 
        .Recipients.Add ("Eugene Astafiev") 
        .Recipients.ResolveAll 
    End With 
 
    'Specify the action in a MoveOrCopyRuleAction object 
    'Action is to move the message to the target folder 
    Set oMoveRuleAction = oRule.Actions.MoveToFolder 
    With oMoveRuleAction 
        .Enabled = True 
        .Folder = oMoveTarget 
    End With 
 
    'Specify the exception condition for the subject in a TextRuleCondition object 
    'Exception condition is if the subject contains "fun" or "chat" 
    Set oExceptSubject = _ 
        oRule.Exceptions.Subject 
    With oExceptSubject 
        .Enabled = True 
        .Text = Array("fun", "chat") 
    End With 
 
    'Update the server and display progress dialog 
    colRules.Save 
End Sub 

huangapple
  • 本文由 发表于 2023年3月31日 23:30:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/75900276.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定