无法使用VBA将附件添加到电子邮件

这个代码我有一个很奇怪的问题。 通用的目的是将Access中的用户数据保存到Excel中的电子表格中,然后使用电子邮件客户端发送包含电子表格附件的电子邮件。 代码如下

Private Sub Send_Email_Click() Dim MySheetPath As String Dim Xl As Excel.Application Dim XlBook As Excel.Workbook Dim XlSheet As Excel.Worksheet ' Tell it location of actual Excel file MySheetPath = "\\SERVER\Users\Public\Documents\WORK ORDERS\Blank Work Order.xlsx" 'Open Excel and the workbook Set Xl = CreateObject("Excel.Application") Set XlBook = GetObject(MySheetPath) 'Make sure excel is visible on the screen Xl.Visible = True XlBook.Windows(1).Visible = True 'Define the sheet in the Workbook as XlSheet Set XlSheet = XlBook.Worksheets(1) 'Insert values in the excel sheet starting at specified cell XlSheet.Range("B6") = Jobnameonform.Value XlSheet.Range("C7") = Companynameonform.Value XlSheet.Range("C8") = Employeename.Value XlSheet.Range("H7") = Jobnumberonform.Value Xl.ActiveWorkbook.Save Xl.ActiveWorkbook.Close Xl.Quit 'in case something goes wrong Set Xl = Nothing Set XlBook = Nothing Set XlSheet = Nothing Dim cdomsg Set cdomsg = CreateObject("CDO.message") With cdomsg.Configuration.Fields .Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2 'NTLM method .Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.gmail.com" .Item("http://schemas.microsoft.com/cdo/configuration/smptserverport") = 587 .Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1 .Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = True .Item("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = 60 .Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "matthewfeeney6@gmail.com" .Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "REDACTED" .Update End With ' build email parts With cdomsg .To = "matthewfeeney6@gmail.com" .From = "matthewfeeney6@gmail.com" .Subject = "Test email" .TextBody = "Did you get the attachment?" .AddAttachment "\\SERVER\Users\Public\Documents\WORK ORDERS\Blank Work Order.xlsx" .Send End With Set cdomsg = Nothing MsgBox "Completed" End Sub 

没有行“.AddAttachment …”代码完全按照预期工作,减去发送附件当然。 但是,使用该行,我得到一个运行时错误91,debugging器引用行“Xl.ActiveWorkbook.Save”作为有问题的代码。 此外,没有修改Excel电子表格的代码,简单的电子邮件部分就可以工作,附件也包括在内。 如果任何人都可以提供见解,为什么我得到这个错误,这将是非常有帮助的。 提前致谢!

编辑:重新testing的代码,它似乎一贯崩溃在Xl.ActiveWorkbook.Save我认为它的工作之前,但我一定是错了

您(认为您)正在保存并closures您的工作簿:

 Xl.ActiveWorkbook.Save Xl.ActiveWorkbook.Close 

但是这不是您正在使用和操作的工作簿,即XlBook

 Set XlBook = GetObject(MySheetPath) 

如果您保存并closures“实际”工作簿, XlBook

 XlBook.Save XlBook.Close 

那么它应该工作。

您在Save调用中得到错误的原因可能意味着Xl.ActiveWorkbook对象不存在/为null或其他东西。