Why does using this closing line of code does not work? - excel

The code stops at the following line working because of the following line
objExcel.Workbooks("cde.XLSX").close
The code properly downloads data from SAP and save it as "cde.xlsx" in a folder location. Once the saving is processed the file opens up by itself and the code is supposed to close it.
The closing step does not to work.
It used to work, did not change anything in the code.
Dim objExcel
Dim objSheet, lastrowRow, i
Set objExcel = GetObject(,"Excel.Application")
Set objSheet = objExcel.Workbooks("Extract_zrep.xlsm").Sheets("Sheet1")
Set lien = objExcel.Workbooks("Extract_zrep.xlsm")
lastrow = objSheet.Range("B65536").End(-4162).Row
SaveToFolder = objSheet.Cells(5, 5).Value
Date1 = Trim(CStr(objSheet.Cells(2, 6).Value))
Date2 = Trim(CStr(objSheet.Cells(2, 8).Value))
session.findById("wnd[0]/tbar[0]/okcd").text = "/nZMM_xxxx"
session.findById("wnd[0]").sendVKey 0
session.findById("wnd[0]/tbar[1]/btn[17]").press
session.findById("wnd[1]/usr/txtV-LOW").text = ""
session.findById("wnd[1]/usr/txtENAME-LOW").text = "USER"
session.findById("wnd[1]/tbar[0]/btn[8]").press
session.findById("wnd[0]/usr/ctxtP_VARI").text = "CDE"
session.findById("wnd[0]/tbar[1]/btn[8]").press
session.findById("wnd[0]/usr/cntlGRID1/shellcont/shell").contextMenu
session.findById("wnd[0]/usr/cntlGRID1/shellcont/shell").selectContextMenuItem "&XXL"
session.findById("wnd[1]/tbar[0]/btn[0]").press
session.findById("wnd[1]/usr/ctxtDY_PATH").text = SaveToFolder
session.findById("wnd[1]/usr/ctxtDY_FILENAME").text = "cde.XLSX"
session.findById("wnd[1]/usr/ctxtDY_FILENAME").caretPosition = 3
session.findById("wnd[1]/tbar[0]/btn[0]").press
objExcel.Workbooks("cde.XLSX").close

Edited:
If you know the workbook in discussion full name, as I suppose, please replace that not working code line with the next code:
Dim objEx As Object, wbFullName As String
wbFullName "C:\your real path\cde.XLSX" 'please, use the real folder path!
Set objEx = GetObject(wbFullName).Application
objEx.Workbooks("cde.XLSX").close
objEx.Quit
It will find and close the new Excel Session, where the workbook is open, close the workbook and quit session...

Related

copying data from sap to excel

Sub invoicenumber1()
Dim SAPGUIAuto As Object '
Dim SAPApplication As Object '
Dim Connection As Object '
Dim session As Object
Set SAPGUIAuto = GetObject("SAPGUI")
Set objGui = SAPGUIAuto.GetScriptingEngine
Set objConn = objGui.Children(0)
Set session = objConn.Children(0)
Dim selectedcountry As String
selectedcountry = ActiveWorkbook.ActiveSheet.Range("D2").Value
session.findById("wnd[0]").maximize
session.findById("wnd[0]/tbar[0]/okcd").Text = "/nvl02"
session.findById("wnd[0]").sendVKey 0
session.findById("wnd[0]/usr/ctxtLIKP-VBELN").Text = selectedcountry
session.findById("wnd[0]/usr/ctxtLIKP-VBELN").caretPosition = 8
session.findById("wnd[0]/tbar[1]/btn[30]").press
session.findById("wnd[0]/usr/shell/shellcont[1]/shell[0]").pressButton "&FIND"
session.findById("wnd[1]/usr/txtLVC_S_SEA-STRING").Text = "invoice"
session.findById("wnd[1]/usr/txtLVC_S_SEA-STRING").caretPosition = 7
session.findById("wnd[1]/tbar[0]/btn[0]").press
session.findById("wnd[1]/tbar[0]/btn[0]").press
session.findById("wnd[1]/tbar[0]/btn[0]").press
session.findById("wnd[0]/tbar[1]/btn[18]").press
session.findById("wnd[1]/usr/ctxtVBUK-VBELN").caretPosition = 10
End Sub
i want to copy text from sap to excel please help me with the given code
i am new to this vba
i want to copy text from this line (session.findById("wnd[1]/usr/ctxtVBUK-VBELN").caretPosition = 10)
add a watch to this (select code in VBA editor and right click -> Add watch) "(session.findById("wnd[1]/usr/ctxtVBUK-VBELN")" then you can see all attributes and you can use them as you want

Excel VBA runs step by step but not in whole

I have written the below code to export data from SAP GUI.
If I go step by step everything works fine. Excel is exported and data is copied to the proper place. But if I try to run it NOT step by step it goes on error (subscript out of range).
The problem is at the 'close SAP session part of the code. from that point the code does not run forward if I try to run it at once. I tried to use a timer which stops the code until the exported file opens but it does not help but I am sure that the problem is that the exported file opens too slowly and the code can't run forward.
Do you have any idea how to solve this? Thanks
Sub SapExport_Returns()
Dim wb As Workbook
Dim ws As Worksheet
Dim ws2 As Worksheet
Dim Wbname As String
'SapExport file is open with Cover sheet filled and Data sheet empty
Set wb = Workbooks("SAP export")
Set ws = wb.Worksheets("Cover")
Set ws2 = wb.Worksheets("Data")
'turn off screen update
Application.ScreenUpdating = False
If Not IsObject(SAPApplication) Then
Set SapGuiAuto = GetObject("SAPGUI")
Set SAPApplication = SapGuiAuto.GetScriptingEngine
End If
If Not IsObject(SAPConnection) Then
Set SAPConnection = SAPApplication.Children(0)
End If
If Not IsObject(SAPsession) Then
Set SAPsession = SAPConnection.Children(0)
End If
If IsObject(WScript) Then
WScript.ConnectObject SAPsession, "on"
WScript.ConnectObject Application, "on"
End If
'Disable the Application Alert before saving the file
Application.DisplayAlerts = False
SAPsession.findById("wnd[0]").maximize
'transaction code
SAPsession.findById("wnd[0]/usr/cntlIMAGE_CONTAINER/shellcont/shell/shellcont[0]/shell").doubleClickNode "F00006"
'company code
SAPsession.findById("wnd[0]/usr/ctxtDD_BUKRS-LOW").Text = CStr(ws.Range("C3").Value)
'open items on date
SAPsession.findById("wnd[0]/usr/ctxtPA_STIDA").Text = ws.Range("H5").Value
'layout
SAPsession.findById("wnd[0]/usr/ctxtPA_VARI").Text = CStr(ws.Range("H8").Value)
SAPsession.findById("wnd[0]/usr/ctxtPA_VARI").SetFocus
SAPsession.findById("wnd[0]/usr/ctxtPA_VARI").caretPosition = 11
SAPsession.findById("wnd[0]/tbar[1]/btn[8]").press
SAPsession.findById("wnd[0]/mbar/menu[0]/menu[3]/menu[1]").Select
'workbook naming
Wbname = CStr(ws.Range("C15").Value)
SAPsession.findById("wnd[1]/usr/ctxtDY_FILENAME").Text = Wbname
SAPsession.findById("wnd[1]/usr/ctxtDY_FILENAME").caretPosition = 8
SAPsession.findById("wnd[1]/tbar[0]/btn[0]").press
'close SAP session
'session.findById("wnd[0]").maximize
'session.findById("wnd[0]/tbar[0]/btn[15]").press
'session.findById("wnd[0]/tbar[0]/btn[15]").press
'Enabling the Application Alerts after saving the file
Application.DisplayAlerts = True
'wait until SAP exported file opens
newHour = Hour(Now())
newMinute = Minute(Now())
newSecond = Second(Now()) + 50
waitTime = TimeSerial(newHour, newMinute, newSecond)
Application.Wait waitTime
'copying formatted data to file and close SAP extract
Workbooks(Wbname).Worksheets("Sheet1").Range("A1").CurrentRegion.Copy ws2.Range("A2")
ws2.Range("A2").CurrentRegion.Columns.AutoFit
ActiveWindow.DisplayGridlines = False
ws2.Name = "FBL5N"
wb.Sheets.Add.Name = "Data"
'Turn on screen update
Application.ScreenUpdating = True
End Sub

Trying to read certain cells from an xls file through access vba. Trouble with dependency on Excel

I am tasked with making a database in microsoft access to which we store parts list. The lists gets delivered in the excel format .xls.
This worksheet has a field header fields ( distinct cells with data) and a list a few rows below. I can get the code to work IF currently there is a normally opened excel file, for instance your personal.XLSB. If Excel is not running, i get issues in the form of
:error 429. activeX can not create object.
or at times an Error 462 in VBA :
remote server machine not found,
application starts with: Cmd_Inlezen_Stuklijst_Import_Click
i have tried to create an instance of excel running in the background by testing if excel is running the function IsExcelRunning
Application.ScreenUpdating = False
Dim src As Workbook
' OPEN THE SOURCE EXCEL WORKBOOK IN "READ ONLY MODE".
Set src = Workbooks.Open(Me!TxtFullPath)
src.Close False ' FALSE - DON'T SAVE THE SOURCE FILE.
Set src = Nothing
sometimes this seems toworks, but i haven't been able to determine exactly how.
i LITERALLY copied https://social.msdn.microsoft.com/Forums/en-US/ffd5975b-83fa-4d64-94af-7230f0058a3d/opening-an-excel-file-from-ms-access?forum=isvvba
then changed the path to the file i need, but as long as excel is NOT running, it doesn't work.
instead of CreateObject, I also tried GetObject but same 429 error
The code in the if statement after i check the status of excel is also according to example. ( source no longer known to me)
I have the references turned on Microsoft Excel 14 object library.
'***************************************************************************
'Purpose: check if excel is running 0 als onwaar -1 als waar
'Inputs
'Outputs: boolean
'***************************************************************************
Public Function IsExcelRunning() As Boolean '
Dim xl As Object
On Error Resume Next
Set xl = GetObject(, "Excel.Application")
IsExcelRunning = (Err.Number = 0)
Set xl = Nothing
End Function
'***************************************************************************
'Purpose: pikt de kop gegevens van het formulier op.
'Inputs:
'A2 leeg
'B2 stuklijstNaam
'C2 editie klant
'D2 Editie Debrug
'E2 Stuklijstomschrijving
'F2 creatiedatum
'G2 ontvangstdatum
'H2 werktijd
'I2 Default aantal
'J2 klant naam
'B3 eindproduct
'B3 eindproduct omschrijving
'Outputs: boolean
'***************************************************************************
Function MiscDataFetch() As Boolean 'leest headers
Dim my_xl_app As Object
Dim my_xl_worksheet As Object
Dim my_xl_workbook As Object
Set my_xl_app = CreateObject("Excel.Application")
my_xl_app.UserControl = True
my_xl_app.Visible = False ' yes. I know it's the default
'WasteTime (2)
Set my_xl_workbook = GetObject(Me!TxtFullPath)
'Set my_xl_workbook = CreateObject(Me!TxtFullPath)
Set my_xl_worksheet = my_xl_workbook.Worksheets(1)
Me!FilStuklijstNaam = my_xl_worksheet.Cells(2, "B")
Me!FilEditieKlant = my_xl_worksheet.Cells(2, "C")
Me!FilEditieDeBrug = my_xl_worksheet.Cells(2, "D")
Me!FilStuklijstOmschrijving = my_xl_worksheet.Cells(2, "E")
Me!FilCreatieDatum = my_xl_worksheet.Cells(2, "F")
Me!FilOntvangstDatum = my_xl_worksheet.Cells(2, "G")
Me!FilWerktijd = my_xl_worksheet.Cells(2, "H")
Me!filDefaultAantal = my_xl_worksheet.Cells(2, "I")
Me!FilKlantNaam = my_xl_worksheet.Cells(2, "J")
Me!FilEindpoduct = my_xl_worksheet.Cells(3, "B")
Me!FilEindproductOmschr = my_xl_worksheet.Cells(3, "E")
my_xl_workbook.Close SaveChanges:=False
Set my_xl_app = Nothing
Set my_xl_workbook = Nothing
Set my_xl_worksheet = Nothing
MiscDataFetch = True
End Function
Sub WasteTime(Finish As Long)
Dim NowTick As Long
Dim EndTick As Long
EndTick = GetTickCount + (Finish * 1000)
Do
NowTick = GetTickCount
GetTickCount = GetTickCount + (1)
Loop Until NowTick >= EndTick
End Sub
'***************************************************************************
'Purpose: controleert de kopgegevens
'Inputs
'Outputs: boolean True: alle gegevens voorzien
' False: er zijn velden nieet ingevuld
'***************************************************************************
Function FullMiscDataFetch() As Boolean
FullMiscDataFetch = True
Dim Fullfilled As Integer
If Me!FilStuklijstNaam = "" Then Fullfilled = Fullfilled + 1
If Me!FilEditieKlant = "" Then Fullfilled = Fullfilled + 1
If Me!FilEditieDeBrug = "" Then Fullfilled = Fullfilled + 1
If Me!FilStuklijstOmschrijving = "" Then Fullfilled = Fullfilled + 1
If Me!FilCreatieDatum = "" Then Fullfilled = Fullfilled + 1
If Me!FilOntvangstDatum = "" Then Fullfilled = Fullfilled + 1
If Me!FilWerktijd = "" Then Fullfilled = Fullfilled + 1
If Me!filDefaultAantal = "" Then Fullfilled = Fullfilled + 1
If Me!FilKlantNaam = "" Then Fullfilled = Fullfilled + 1
If Me!FilEindpoduct = "" Then Fullfilled = Fullfilled + 1
If Me!FilEindproductOmschr = "" Then Fullfilled = Fullfilled + 1
If Fullfilled > 1 Then
MsgBox "Niet alle detailvelden bevatten gegevens." & vbCrLf & "Vul de gegevens aan en probeer opnieuw."
FullMiscDataFetch = False
End If
End Function
'***************************************************************************
'Purpose: inleescommando voor deze pagina (Frm_stuklijst_Import).
'Inputs
'Outputs:
'***************************************************************************
Private Sub Cmd_Inlezen_Stuklijst_Import_Click() 'commando voor lijst MET headers
Dim SQLKlantUpdate As String
Dim SQLKlantIDUpdate As String
'DoCmd.RunSQL "DELETE * FROM Tbl_Stuklijst_Import" 'opschonen werkblad
'opschonen
'SubFrm_Tbl_Stuklijst_Import.Requery 'updaten van visueel gegeven lege lijst
If IsExcelRunning Then
Else
'Application.ScreenUpdating = False
'Dim src As Workbook
' OPEN THE SOURCE EXCEL WORKBOOK IN "READ ONLY MODE".
'Set src = Workbooks.Open(Me!TxtFullPath)
'src.Close False ' FALSE - DON'T SAVE THE SOURCE FILE.
'Set src = Nothing
End If
MiscDataFetch 'get header comments
'FetchData 'get material list
FullMiscDataFetch 'controle of alle velden info bevatten
End Sub
expected result is that the distinct cells are read and transferred to fields in the form, whether excel is running or not, and without the need for the user to intervene by activating Excel to bypass the error.
I need to somehow catch the difference in method whether excel is running or not.
Try this to open and close an Excel file:
Dim xl As Excel.Application
Dim xlBook As Excel.workbook
Dim xlSheet As Excel.worksheet
Set xl = New Excel.Application
Set xlBook = xl.Workbooks.Open(Filename)
Set xlSheet = xlBook.Worksheets(1)
…
xlBook.Close
Set xlSheet = Nothing
Set xlBook = Nothing
Set xl = Nothing
If you are using types of Excel as in
Dim wb As Excel.Workbook
then you must have a reference to Excel; however, if you are working with Late Binding as in
Dim wb As Object 'Excel.Workbook
Then remove the reference to Excel. This has the advantage that your code will work with different versions of Excel. Otherwise you are tied to a specific version. Often I use early binding (first method) during development and then switch to Object for all library-specific types and remove the reference. This makes the Access application more stable.
I usually use this code to get the application. If the application is open I return it (GetObject), otherwise I create it (CreateObject). Here shown with Word:
Public Function GetWordApplication() As Object
'Gets an active Word application or opens a new Word instance.
'Raises Error No. 8 if word cannot be opened.
On Error Resume Next
'Find existing instance of Word
Set GetWordApplication = GetObject(, "Word.Application")
If Err.Number <> 0 Then 'Not found, create new instance.
Set GetWordApplication = CreateObject("Word.Application")
End If
On Error GoTo 0
If GetWordApplication Is Nothing Then
Err.Raise 8, "YourApp.GetWordApplication", "Word could not be opened."
End If
End Function

Not able to bypass Run time error 619 in SAP connection

I have a macro to download certain SAP reports to Excel. My issue is that if I run the macro more than once in the same SAP session (first time it works fine), I get a Run time error 619 which I am not able to bypass.
For some reason (I think it's related to which server the user is logged on to), the SAP module (RE-FX) have two different variants/GUIs. Therefore, I have two different setups for downloading the report to Excel depending on the variant/GUI.
I am using the On Error Goto statement to shift between those two variants. The Run time error appears in the line following the On Error Goto statement.
As mentioned, this works fine the first time I run the macro (no Run Time error occurs and the macro jumps to the error handler as expected), but the second time I run it, the error '619' appears and it is not possible to bypass it.
I have tried the solution in this post (including Application.Wait):
Cannot Bypass Error 619 [executing SAP from VBA]
But that did not fix it (it is not the timing which is the issue here).
Sub Run_REISCDCF()
Dim Filepath As String
Dim ReportDate As String
Dim SapGuiAuto As Object
Dim SAPApp As Object
Dim SAPCon As Object
Dim session As Object
Filepath = ThisWorkbook.Sheets("Guide").Cells(5, 5).Text 'place to store SAP reports
'Create connection to SAP
'------------------------------------------
Set SapGuiAuto = GetObject("SAPGUI")
Set SAPApp = SapGuiAuto.GetScriptingEngine
Set SAPCon = SAPApp.Children(0)
Set session = SAPCon.Children(0)
'------------------------------------------
'Removed some code to run the report and change layout (which works fine)
'Save to Excel
session.findById("wnd[0]/usr/subSUB_AREA_ROOT:SAPLREIS_GUI_CONTROLLER:0200/subSUB_AREA:SAPLREIS_GUI_CONTROLLER:1000/cntlCC_LIST/shellcont/shell").pressToolbarContextButton "&MB_EXPORT"
session.findById("wnd[0]/usr/subSUB_AREA_ROOT:SAPLREIS_GUI_CONTROLLER:0200/subSUB_AREA:SAPLREIS_GUI_CONTROLLER:1000/cntlCC_LIST/shellcont/shell").selectContextMenuItem "&XXL"
On Error GoTo XLSX_variant 'SAP has two different GUI's for RE-FX with one of them only allowing to download to a MHTML file type
session.findById("wnd[1]/usr/ctxtDY_PATH").Text = "Filepath" '<-- At this line the Run Time error appears
session.findById("wnd[1]/usr/ctxtDY_FILENAME").Text = "REISCDCF.MHTML"
session.findById("wnd[1]/tbar[0]/btn[11]").press
Exit Sub
XLSX_variant:
session.findById("wnd[1]/tbar[0]/btn[0]").press
session.findById("wnd[1]/usr/ctxtDY_PATH").Text = "Filepath"
session.findById("wnd[1]/usr/ctxtDY_FILENAME").Text = "REISCDCF.XLSX"
session.findById("wnd[1]/tbar[0]/btn[11]").press
Exit Sub
Try this...
If Not session.findById("wnd[1]/tbar[0]/btn[0]", False) Is Nothing Then
session.findById("wnd[1]/tbar[0]/btn[0]").press
End If
This code will lookup for the button in the session you are and if it finds it it will click on it else it means it’s not there and I’ll continue with next line.
Sub Run_REISCDCF()
Dim Filepath As String
Dim ReportDate As String
Dim SapGuiAuto As Object
Dim SAPApp As Object
Dim SAPCon As Object
Dim session As Object
Filepath = ThisWorkbook.Sheets("Guide").Cells(5, 5).Text 'place to store SAP reports
'Create connection to SAP
'------------------------------------------
Set SapGuiAuto = GetObject("SAPGUI")
Set SAPApp = SapGuiAuto.GetScriptingEngine
Set SAPCon = SAPApp.Children(0)
Set session = SAPCon.Children(0)
'------------------------------------------
'Removed some code to run the report and change layout (which works fine)
'Save to Excel
session.findById("wnd[0]/usr/subSUB_AREA_ROOT:SAPLREIS_GUI_CONTROLLER:0200/subSUB_AREA:SAPLREIS_GUI_CONTROLLER:1000/cntlCC_LIST/shellcont/shell").pressToolbarContextButton "&MB_EXPORT"
session.findById("wnd[0]/usr/subSUB_AREA_ROOT:SAPLREIS_GUI_CONTROLLER:0200/subSUB_AREA:SAPLREIS_GUI_CONTROLLER:1000/cntlCC_LIST/shellcont/shell").selectContextMenuItem "&XXL"
'SAP has two different GUI's for RE-FX with one of them only allowing to download to a MHTML file type
If Not session.findById("wnd[1]/tbar[0]/btn[0]", False) Is Nothing Then
session.findById("wnd[1]/tbar[0]/btn[0]").press
End If
session.findById("wnd[1]/usr/ctxtDY_PATH").Text = "Filepath" '<-- At this line the Run Time error appears
session.findById("wnd[1]/usr/ctxtDY_FILENAME").Text = "REISCDCF.MHTML"
session.findById("wnd[1]/tbar[0]/btn[11]").press
Exit Sub
Thanks to #reFractil for coming up with a solution that worked!
I had to edit his solution slightly in order to embed the two variants (download SAP report as .XLSX or .MHTML), but the structure and code proposed by reFractil is the same:
'Changed code only below
'Save to Excel
session.findById("wnd[0]/usr/subSUB_AREA_ROOT:SAPLREIS_GUI_CONTROLLER:0200/subSUB_AREA:SAPLREIS_GUI_CONTROLLER:1000/cntlCC_LIST/shellcont/shell").pressToolbarContextButton "&MB_EXPORT"
session.findById("wnd[0]/usr/subSUB_AREA_ROOT:SAPLREIS_GUI_CONTROLLER:0200/subSUB_AREA:SAPLREIS_GUI_CONTROLLER:1000/cntlCC_LIST/shellcont/shell").selectContextMenuItem "&XXL"
'Solution:
If Not session.findById("wnd[1]/tbar[0]/btn[0]", False) Is Nothing Then
session.findById("wnd[1]/tbar[0]/btn[0]").press
session.findById("wnd[1]/usr/ctxtDY_PATH").Text = Filepath
session.findById("wnd[1]/usr/ctxtDY_FILENAME").Text = "REISCDCF.XLSX" 'Download as .XLSX if in "XLSX SAP_variant"
session.findById("wnd[1]/tbar[0]/btn[11]").press
Exit Sub
End If
session.findById("wnd[1]/usr/ctxtDY_PATH").Text = Filepath
session.findById("wnd[1]/usr/ctxtDY_FILENAME").Text = "REISCDCF.MHTML" 'Download as .MHTML if in "MHTML SAP_variant"
session.findById("wnd[1]/tbar[0]/btn[11]").press
Exit Sub

Can't add attachment to email using VBA

I am having a very strange problem with this code. The general purpose is to save user data from a form in Access to a spreadsheet in Excel, and then use an email client to send an email containing the spreadsheet attachment. The code is as follows
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
Without the line ".AddAttachment..." The code works exactly as intended, minus sending the attachment of course. However, with that line, I get a runtime error 91, with the debugger citing the line "Xl.ActiveWorkbook.Save" as the problematic code. Also, without the code to modify the excel spreadsheet, the simple email portion does work, attachments included. If anyone can provide insight as to why I am getting this error, that would be very helpful. Thanks in advance!
EDIT: Retesting the code, it seems to consistently crash at Xl.ActiveWorkbook.Save I thought it worked before, but I must have been mistaken
You (think you) are saving and closing your workbook with:
Xl.ActiveWorkbook.Save
Xl.ActiveWorkbook.Close
but that's not the workbook you're using and manipulating, which is XlBook:
Set XlBook = GetObject(MySheetPath)
If you save and close the "real" workbook, XlBook:
XlBook.Save
XlBook.Close
then it should work.
The reason you're getting the error at the Save call probably means that the Xl.ActiveWorkbook object doesn't exist/is null or something.

Resources