创建规则时出现编译错误(参数不可选)

问题描述 投票:0回答:1

我正在尝试编写一个 VBA 脚本,将所有选定电子邮件的域添加到 Outlook 中的阻止发件人列表中。

我收到错误:

编译错误:
参数不是可选的。

Set blockedSendersRule = blockedSenders.Create("Blocked Domains")

Error Message

Sub AddDomainsToBlockedSendersList()
    Dim olSelection As Selection
    Dim olItem As Object
    Dim olApp As Outlook.Application
    Dim olNamespace As Outlook.NameSpace
    Dim blockedSenders As Outlook.Rules
    Dim blockedSendersRule As Outlook.Rule
    Dim domainList As Collection
    Dim domain As String
    Dim msg As String
    
    ' Initialize Outlook objects
    Set olApp = Outlook.Application
    Set olNamespace = olApp.GetNamespace("MAPI")
    Set blockedSenders = olNamespace.DefaultStore.GetRules()
    Set domainList = New Collection
    
    ' Get selected emails
    Set olSelection = olApp.ActiveExplorer.Selection
    
    ' Loop through selected emails
    For Each olItem In olSelection
        If olItem.Class = olMail Then
            domain = GetDomainFromEmail(olItem.SenderEmailAddress)
            If Not IsDuplicate(domain, domainList) Then
                domainList.Add domain
            End If
        End If
    Next olItem
    
    ' Add domains to blocked senders list
    If domainList.Count > 0 Then
        Set blockedSendersRule = blockedSenders.Create("Blocked Domains")
        
        For Each domain In domainList
            blockedSendersRule.Conditions.From.Recipients.Add domain
        Next domain
        
        blockedSendersRule.Enabled = True
        blockedSenders.Save
        msg = "Domains added to the Blocked Senders list."
    Else
        msg = "No valid domains found in selected emails."
    End If
    
    ' Display a message box
    MsgBox msg, vbInformation, "Add Domains to Blocked Senders List"
End Sub

Function GetDomainFromEmail(email As String) As String
    Dim parts() As String
    parts = Split(email, "@")
    If UBound(parts) = 1 Then
        GetDomainFromEmail = parts(1)
    Else
        GetDomainFromEmail = ""
    End If
End Function

Function IsDuplicate(domain As String, domainList As Collection) As Boolean
    On Error Resume Next
    domainList.Add domain, CStr(domain)
    IsDuplicate = (Err.Number = 457) ' 457 = "Key is already associated with an element of this collection"
    Err.Clear
    On Error GoTo 0
End Function

添加

olRuleReceive
修复了此行。

vba outlook
1个回答
0
投票

根据@BigBen的评论,

Rules.Create
必须传递两个参数,规则的名称和规则的类型,在您的情况下可能是
olRuleReceive
使相关行
Set blockedSendersRule = blockedSenders.Create("Blocked Domains", olRuleReceive)
。请参阅此处的 MS 文档 Rules.Create 和此处 OlRuleType

© www.soinside.com 2019 - 2024. All rights reserved.