2013-06-28 81 views
3

任何人都可以告訴我爲什麼我在下面的函數中收到「運行時錯誤'91'」消息嗎?它的發生在這條線:運行時錯誤'91'&Outlook.Application = <Object variable或With block variable not set>?

Set olMailItem = olApp.CreateItem(olMailItem) 

而且,只要我在調試,我把我的光標移到此行,訪問給我這個消息:「Outlook.Application =沒有設置<對象變量或With塊變量>「:

Dim olApp As New Outlook.Application 

我試圖創建一個按鈕,將打開的Outlook電子郵件信息,並允許將數據錄入員在發送前編輯消息。我檢查了我的引用,並且檢查了Microsoft Outlook 14.0 Object Library。

此外,如果您對提高代碼效率有任何建議,請分享。我對Access編程相當陌生。

Private Sub EmailButton_Click() 
    Dim EmailThis As String 

    EmailThis = CreateEmailWithOutlook("[email protected]", "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 

回答

4

的問題是,在啓用了展望庫參考,olMailItem是保留不變,我認爲當你Dim olMailItem as Outlook.MailItem這不是一個問題,而是試圖設置變量導致問題。

以下是完整的解釋:

您已經聲明olMailItem作爲一個對象變量。

  • 賦值語句的右邊,你要引用這個設置Object之前,它的值對象的實例。這基本上是一個遞歸錯誤,因爲你有對象試圖自己分配自己。
  • 還有另外一個潛在的錯誤,如果olMailItem此前被分配,這種說法會提高其他錯誤(可能是一個Mismatch錯誤,因爲不斷olMailItem是一個整數,但通過恰當地使用這個名字,你可以通過傳遞引入的失配誤差一個Object其中一個Integer預計

嘗試改變,這個變量olMailItem的別的東西,像mItem此代碼是在Excel 2010中,Windows 7的測試,我認爲它應該用於訪問工作,太。:

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 
+0

這解決了它!謝謝大衛! – candyA