Não pode adicionar anexos a e-mail usando o VBA
-
02-01-2020 - |
Pergunta
Eu estou tendo um problema muito estranho com esse código.O objetivo geral é para salvar dados do usuário a partir de um formulário do Access para uma planilha no Excel e, em seguida, usar um cliente de e-mail para enviar um e-mail contendo a planilha em anexo.O código é o seguinte
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
Sem a linha ".AddAttachment..." O código funciona exatamente como pretendido, menos enviar o anexo de curso.No entanto, com essa linha, eu recebo um erro de tempo de execução 91, com o depurador citando a linha "Xl.ActiveWorkbook.Guardar" como o código problemático.Também, sem o código para modificar a folha de cálculo do excel, o simples e-mail faz parte do trabalho, os anexos incluídos.Se alguém pode fornecer insight sobre o porquê eu estou recebendo este erro, que seria muito útil.Obrigado antecipadamente!
EDITAR:Voltou a testar o código, parece consistentemente falha no Xl.ActiveWorkbook.Guardar eu pensei que ele trabalhou antes, mas eu devo ter sido enganado
Solução
Você (acha que) são salvar e fechar a pasta de trabalho com:
Xl.ActiveWorkbook.Save
Xl.ActiveWorkbook.Close
mas esse não é o livro que está a utilizar e manipular, o que é XlBook
:
Set XlBook = GetObject(MySheetPath)
Se você salva e fechar o "real" pasta de trabalho, XlBook
:
XlBook.Save
XlBook.Close
em seguida, ele deve funcionar.
A razão pela qual você está recebendo o erro no Save
chamada provavelmente significa que a Xl.ActiveWorkbook
o objeto não existe/é nulo ou algo assim.