【发布时间】:2020-07-13 21:25:12
【问题描述】:
这段代码有一个非常奇怪的问题。通用目的是将 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,调试器将“Xl.ActiveWorkbook.Save”行引用为有问题的代码。此外,无需修改 Excel 电子表格的代码,简单的电子邮件部分就可以工作,包括附件。如果有人可以提供有关我为什么会收到此错误的见解,那将非常有帮助。提前致谢!
编辑:重新测试代码,它似乎一直在 Xl.ActiveWorkbook.Save 崩溃我认为它以前工作过,但我一定是弄错了
【问题讨论】:
-
您是在告诉我,如果您添加行
.AddAttachment "",它会在Xl.ActiveWorkbook.Save处崩溃,而没有它它运行良好?! VBA 是一个逐行程序,它不可能在您修改某些内容之前崩溃(例如,在最后添加一些内容不会在到达之前崩溃......) -
编辑:我刚刚重新测试了代码。我错了。它在 Xl.ActiveWorkbook.Save 处不断崩溃
-
@user3656992 我感觉您正在尝试将包含上述代码的工作簿附加到电子邮件中?