【问题标题】:MailItem Sent Invalid UseMailItem 发送无效使用
【发布时间】:2016-07-18 17:03:02
【问题描述】:


背景

question here 提供了进一步的解释。
在这种情况下,我想知道为什么如果我将电子邮件设置为对象,我会在MailItem.Sent Property 中收到“无效使用属性”的错误。
问题

通过向项目添加 Outlook 引用:
错误代码无效使用属性(.Sent):
SetEmailAsObjectCode

Dim olApp As Object: Set olApp = CreateObject("Outlook.Application")
Dim EmailToSend As Object
Set EmailToSend = Nothing
    Set EmailToSend = olApp.CreateItem(0)
    With EmailToSend
    On Error Resume Next
    Call .Sent
    If Err.Number = 0 Then ' 4. If Err.Number = 0
    Cells(1,1).Value = "ErrorOutLookTimeout: Email not sent"
    Else ' 4. If Err.Number = 0
    Cells(1,1).Value = "Email Sent!"
    End If ' 4. If Err.Number = 0
    On Error GoTo 0
    End With

工作代码:
SetCreateItemObjectCode

Dim olApp As Outlook.Application: Set olApp = CreateObject("Outlook.Application")
    Dim EmailToSend As Outlook.MailItem
    Set EmailToSend = Nothing
        Set EmailToSend = olApp.CreateItem(0)
        With olApp.CreateItem(0)
        On Error Resume Next
        Call .Sent
        If Err.Number = 0 Then ' 4. If Err.Number = 0
        Cells(1, 1).Value = "ErrorOutLookTimeout: Email not sent"
        Else ' 4. If Err.Number = 0
        Cells(1, 1).Value = "Email Sent!"
        End If ' 4. If Err.Number = 0
        On Error GoTo 0
        End With

您可能会注意到,它没有引用创建的电子邮件对象,而是立即设置
问题:

为什么代码 SetCreateItemObjectCode 有效而 SetEmailAsObjectCode 无效?

【问题讨论】:

    标签: excel vba outlook


    【解决方案1】:

    CreateItem 返回一个对象。 Outlook.MailItem 本身是一个类,而当您执行 Set EmailToSend = olApp.CreateItem(0) 时,尽管 EmailToSend 变量可以容纳返回的 Object ,但它不再公开 .Sent 属性。因此错误。

    使用这个:

    With EmailToSend
    On Error Resume Next
    Call .ItemProperties.Item("Sent")
    

    【讨论】:

    • 我明白了,我认为这与我尚未完全理解的 OOP 逻辑的缺失部分有关,谢谢!
    【解决方案2】:

    如果您尝试发送消息,则需要调用MailItem.Send 方法。如果您想查明邮件是草稿还是已发送邮件,请阅读 MailItem.Sent 属性。

    注意“d”与“t”。

    【讨论】:

    • 我正在检查消息是否已发送;这是通过 SetCreateItemObjectCode 实现的,但是,我在 SetEmailAsObjectCode 中收到错误“无效使用属性”,我想知道为什么,因为他们都可能在 With 语句中使用相同的对象
    • 正确的语法应该是“if EmailToSend.Sent then...”。但是,在您的情况下,消息只是使用 CreateItem 创建的,当然它不会发送。
    • 既然With从一开始我就看不出为什么要再次添加它的逻辑,你能解释一下为什么吗? With EmailToSend .... EmailToSend.Sent ... End With?
    • 您没有抓住重点——调用方法或子程序时使用了“调用”。对于布尔属性,它必须是表达式的一部分,例如“if..then”。您可以使用“if EmailToSend.Sent then...”或“if .Sent then...”。,它使差异为零。再一次,Sent 属性检查在这里没有任何意义 - 消息未发送。直到它被移动到已发送邮件文件夹。但到那时它将是具有不同条目 id 的不同项目。
    • 我在发布if EmailToSend.Sent then...之前按照建议尝试过,它总是返回false。
    猜你喜欢
    • 1970-01-01
    • 2017-04-04
    • 2017-04-12
    • 1970-01-01
    • 1970-01-01
    • 2016-02-24
    • 1970-01-01
    • 1970-01-01
    • 2012-06-17
    相关资源
    最近更新 更多