我对这段代码有一个非常奇怪的问题。一般用途是将 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 崩溃 我以为它以前有效,但我一定是弄错了

有帮助吗?

解决方案

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

Xl.ActiveWorkbook.Save
Xl.ActiveWorkbook.Close

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

Set XlBook = GetObject(MySheetPath)

如果您保存并关闭“真实”工作簿, XlBook:

XlBook.Save
XlBook.Close

那么它应该可以工作。

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top