簡體   English   中英

從 Excel VBA 通過 Outlook 發送電子郵件時出錯

[英]Error While Sending Email through Outlook from Excel VBA

我在 Outlook 和 excel vba 中寫了一個宏,描述是: 1. 如果電子郵件主題行匹配,則在 Outlook 中打開 Excel 文件的代碼:

Private Sub Items_ItemAdd(ByVal Item As Object)
    If TypeOf Item Is Outlook.MailItem Then
        '// Subject line here
        If InStr(Item.Subject, "Run Dashboard") Then
            Call openExcel
        End If
    End If
End Sub

一旦 Excel 打開並運行儀表板,則必須通過 excel 發送電子郵件。

vba和代碼:

Dim outapp As Object
Dim nmail As Object

Set outapp = CreateObject("Outlook.Application")
Set nmail = outapp.CreateItem(0)
With nmail
    .To = "xxxxxx@xxxx.com"
    .cc = ""
    .bcc = ""
    .Subject = flname
    .htmlbody = RangetoHTML(Range("A1:" & Split(Cells(, lastcol1).Address, "$")(1) & lastrow1))
    .attachments.Add ActiveWorkbook.FullName
    .display
End With

On Error GoTo 0

Set nmail = Nothing

Set outapp = Nothing

現在我面臨Set outapp = CreateObject("Outlook.Application")錯誤這個錯誤只顯示如果我通過 Outlook 電子郵件打開 excel 文件,如第 1 點所述,如果我以正常方式打開文件,即沒有 Outlook 幫助,然后代碼運行成功。

請幫忙。

提前致謝

為什么需要從 Outlook 自動化 Excel,然后從 Excel 自動化 Outlook?

 Set outapp = CreateObject("Outlook.Application")

相反,您可以獲得正在運行的 Outlook 實例(如果有),因為只有一個 Outlook 實例可以同時運行。 有關詳細信息,請參閱如何從另一個程序自動化 Outlook以及Office 自動化服務器的 GetObject 和 CreateObject 行為

嘗試改用以下代碼行:

 Set nmail = Application.CreateItem(olMailItem)

如果您在 Outlook 中配置了多個配置文件,您很可能需要使用 Namespace 類的Logon方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM