运行时错误'91'&amp; Outlook.Application = <object variable =“”或=“”with =“”block =“”variable =“”not =“”set =“”>?</object>

时间:2013-06-28 12:23:15

标签: vba ms-access-2010

有谁可以告诉我为什么我在下面的函数中收到“运行时错误'91'”消息?它发生在这条线上:

Set olMailItem = olApp.CreateItem(olMailItem)

此外,每当我进行调试并将光标放在此行上时,Access就会给出以下消息:“Outlook.Application =&lt; Object variable或With block variable not set&gt;”:

Dim olApp As New Outlook.Application 

我正在尝试创建一个按钮,该按钮将打开Outlook电子邮件,并允许数据录入员在发送之前编辑该邮件。我检查了我的引用,并检查了Microsoft Outlook 14.0对象库。

另外,如果您对提高我的代码效率有任何建议,请分享。我是Access编程的新手。

Private Sub EmailButton_Click()
    Dim EmailThis As String

    EmailThis = CreateEmailWithOutlook("myname@company.com", "Testing e-mail Access database", "This is a test")
    DoCmd.SendObject acSendForm, "SubmitNewIdeaForm", , "My Name", , "Test", , True
    On Error GoTo CreateEmail_Exit

CreateEmail_Exit:
    Exit Sub

End Sub

Public Function CreateEmailWithOutlook(MessageTo As String, Subject As String, MessageBody As String)

    ' Define app variable and get Outlook using the "New" keyword
    Dim olApp As New Outlook.Application
    Dim olMailItem As Outlook.MailItem  ' An Outlook Mail item

    Set olApp = CreateObject("Outlook.Application")
    ' Create a new email object
    Set olMailItem = olApp.CreateItem(olMailItem)

    ' Add the To/Subject/Body to the message and display the message
    With olMailItem
        .To = MessageTo
        .Subject = Subject
        .Body = MessageBody
        .Display    ' To show the email message to the user
    End With

    ' Release all object variables
    Set olMailItem = Nothing
    Set olApp = Nothing

End Function

1 个答案:

答案 0 :(得分:5)

问题是,在启用Outlook库引用的情况下,olMailItem是一个保留常量,我认为当你Dim olMailItem as Outlook.MailItem没有问题时,但是尝试设置变量是导致的一个问题。

以下是完整的解释:

您已将olMailItem声明为对象变量。

  • 在赋值语句的右侧,在将其值设置为对象的实例之前,您将引用此Object。这基本上是一个递归错误,因为你有对象试图自己分配自己。
  • 还有另一个潜在错误,如果先前已分配olMailItem,则此语句会引发另一个错误(可能是Mismatch错误,因为常量olMailItem是一个整数但是使用这个名称不恰当,您可能会在Object传递Integer时引入不匹配错误。

尝试将此变量的名称olMailItem更改为其他内容,例如mItem。此代码在Excel 2010,Windows 7中进行了测试,我认为它也适用于Access:

Dim olApp As New Outlook.Application
Dim mItem As Outlook.MailItem  ' An Outlook Mail item

Set olApp = CreateObject("Outlook.Application")
Set mItem = olApp.CreateItem(olMailItem)
' Add the To/Subject/Body to the message and display the message
With mItem
    .To = MessageTo
    .Subject = Subject
    .Body = MessageBody
    .Display    ' To show the email message to the user
End With

' Release all object variables
Set mItem = Nothing
Set olApp = Nothing