从Excel VBA通​​过Outlook发送电子邮件时出错

时间:2015-10-20 07:19:11

标签: vba excel-vba outlook-vba excel

我在outlook和excel vba中编写了一个宏,描述如下: 1.如果电子邮件主题行匹配,Outlook for Open 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帮助,则代码正在成功运行。

请帮助。

提前致谢

1 个答案:

答案 0 :(得分:0)

为什么需要从Outlook自动Excel,然后从Excel自动化Outlook?

 Set outapp = CreateObject("Outlook.Application")

相反,您可能会获得正在运行的Outlook实例(如果有),因为只能同时运行一个Outlook实例。有关详细信息,请参阅How to automate Outlook from another programGetObject and CreateObject behavior of Office automation servers

尝试使用以下代码行:

 Set nmail = Application.CreateItem(olMailItem)

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

相关问题