声明WithEvents变量 - 编译错误:Sub或Function中的无效特性"

时间:2016-08-25 12:15:50

标签: vba outlook outlook-vba

我有两组代码。第一个代码添加由按钮触发的预设BCC地址。第二个代码可以通过标记/分类发送的电子邮件,复制发送的电子邮件,然后将副本移动到pickfolder中指示的文件夹来提交电子邮件。

这两个代码分开工作。

当我在ThisOutlookSession中粘贴两个代码时,第二个代码不起作用。错误是(从荷兰语松散翻译):"编译错误:Sub或Function"中的无效特征;这涉及所有三个声明(Dim WithEvents objInspectors As Inspectors, Dim WithEvents objMyNewMail As MailItem, Dim WithEvents colSentItems As Items

完整代码:

'button bcc to crm system emailaddress)

Sub AddCRMtoBCC()
    Dim objRecip As Recipient
    Set oMsg = Application.ActiveInspector.CurrentItem
    With oMsg
        Set objRecip = oMsg.Recipients.Add("__@__.com")
        objRecip.Type = olBCC
        objRecip.Resolve
    End With
    Set oMsg = Nothing
End Sub
'________


'file emails

Dim WithEvents objInspectors As Inspectors
Dim WithEvents objMyNewMail As MailItem
Dim WithEvents colSentItems As Items

Private Sub Application_Startup()
    Set objInspectors = Application.Inspectors
    Dim NS As Outlook.NameSpace
    Set NS = Application.GetNamespace("MAPI")
    Set colSentItems = NS.GetDefaultFolder(olFolderSentMail).Items
    Set NS = Nothing
End Sub

Private Sub Application_Quit()
    Set objInspectors = Nothing
    Set objMyNewMail = Nothing
End Sub

Private Sub objInspectors_NewInspector(ByVal Inspector As Inspector)
    If Inspector.CurrentItem.Class <> olMail Then Exit Sub
    Set objMyNewMail = Inspector.CurrentItem
End Sub

Private Sub objMyNewMail_Send(Cancel As Boolean)
    If MsgBox("Are you sure you want to send this message?", vbYesNo + vbQuestion _
        , "SEND CONFIRMATION") = vbNo Then
        Cancel = True
    End If
End Sub

Private Sub colSentItems_ItemAdd(ByVal Item As Object)
    If Item.Class = olMail Then
        Set Copy = Item.Copy
        Set objNS = Application.GetNamespace("MAPI")
        Set objFolder = objNS.PickFolder
        Copy.Move objFolder
    End If
End Sub

2 个答案:

答案 0 :(得分:1)

当你在模块级别声明全局变量时(ThisOutlookSession是一个模块),所有这些都应该在模块的顶部声明。

因此,在第一个sub()

之前,将这3行移到顶部
Dim WithEvents objInspectors As Inspectors
Dim WithEvents objMyNewMail As MailItem
Dim WithEvents colSentItems As Items

答案 1 :(得分:0)

objMyNewMail_Send()取消参数必须声明为ByRef