运行时错误'91'和Outlook.Application = <对象变量或没有设置块变量>?

can*_*dyA 6 vba ms-access-2010

任何人都可以告诉我为什么我在下面的函数中收到"运行时错误'91'"消息?它发生在这条线上:

Set olMailItem = olApp.CreateItem(olMailItem)
Run Code Online (Sandbox Code Playgroud)

此外,每当我在调试并将光标放在此行上时,Access会给我这样的消息:"Outlook.Application = <Object variable或With block variable not set>":

Dim olApp As New Outlook.Application 
Run Code Online (Sandbox Code Playgroud)

我正在尝试创建一个按钮,该按钮将打开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
Run Code Online (Sandbox Code Playgroud)

Dav*_*ens 6

问题是,在启用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
Run Code Online (Sandbox Code Playgroud)