質問

このコードには非常に奇妙な問題があります。汎用目的は、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
.

しかし、それはあなたが使用していて操作しているワークブックではありません。

Set XlBook = GetObject(MySheetPath)
.

「Real」ブックを保存して閉じる場合、XlBook

XlBook.Save
XlBook.Close
.

それはうまくいくべきです。

XlBook呼び出しでエラーが発生しているのはおそらくSaveオブジェクトが存在しないことを意味します。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top