Not able to bypass Run time error 619 in SAP connection - excel

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

Related

How can I solve the Compilation error: syntax error on my VBA sub?

I have this sub that are calling for execute other two subs in the program, but when I try to execute it pops up the Compilation error: syntax error right on the fisrt line of the sub.
Sub MacroPrimaria()
Call SAPOpenSessionFromLogon
Application.Wait Now + TimeValue("00:00:05")
Call executarsap
MsgBox ("PROCESSAMENTO FINALIZADO")
End Sub
Sub SAPOpenSessionFromLogon()
Dim SapGui
Dim Applic
Dim connection
Dim session
Dim WSHShell
Shell "C:\Program Files (x86)\SAP\FrontEnd\SAPgui\saplogon.exe", vbNormalFocus
Set WSHShell = CreateObject("WScript.Shell")
Do Until WSHShell.AppActivate("SAP Logon ")
Application.Wait Now + TimeValue("0:00:01")
Loop
Set WSHShell = Nothing
Set SapGui = GetObject("SAPGUI")
Set Applic = SapGui.GetScriptingEngine
Set connection = Applic.OpenConnection("S/4 HANA - PRODUÇÃO", True)
Set session = connection.Children(0)
session.findById("wnd[0]").maximize
End Sub
Sub executarsap()
Dim Application, SapGuiAuto, connection, session, WScrip
'**IMPORTANTE**: Abaixo daqui, basta colar o scrip gerado pela gravação do SAP, sem retirar nada:
'This sub it's okay and has confidential stuff so its just to know.
End Sub
I'm gettin stuck with this error on the lines:
"Sub MacroPrimaria()"
"Sub SAPOpenSessionFromLogon()"
I'm expecting to get able to execute the macro
Your code isn't giving a compile error for me.
This is the code I use to interact with SAP and it hasn't given me any problems so far (can't remember where I found it on the Internet though).
It may help.
Public Sub Execute_SAP()
'Login details here.
Dim LogInDetail As Variant
LogInDetail = Array("***YOUR USER NAME***", "***YOUR PASSWORD***")
'Open the SAP Log-In screen and wait for it to load.
Shell "C:\Program Files (x86)\SAP\FrontEnd\SAPgui\saplogon.exe", 4
Dim WshShell As Object
Set WshShell = CreateObject("WScript.Shell")
Do Until WshShell.AppActivate("SAP Logon ")
Application.Wait Now + TimeValue("0:00:01")
Loop
Set WshShell = Nothing
Dim SAPGui As Object
Set SAPGui = GetObject("SAPGUI")
Dim Appl As Object
Set Appl = SAPGui.GetScriptingEngine
Dim Connection As Object
Set Connection = Appl.OpenConnection("S/4 HANA - PRODUÇÃO", True)
Dim Session As Object
Set Session = Connection.Children(0)
With Session
'Log-in to the session.
.findById("wnd[0]/usr/txtRSYST-MANDT").Text = "300"
'The next two lines accept the username and password - LogInDetail variant holds those two values.
.findById("wnd[0]/usr/txtRSYST-BNAME").Text = LogInDetail(0)
.findById("wnd[0]/usr/pwdRSYST-BCODE").Text = LogInDetail(1)
.findById("wnd[0]/usr/txtRSYST-LANGU").Text = "EN"
.findById("wnd[0]").maximize
.findById("wnd[0]").SendVKey 0 'ENTER
'Rest of SAP code - each line starts with
' .findById("wnd[0]
'Use SAPs macro recorder to get the detail... is probably what you've got in executearsap()
End With
End Sub
thanks for the help!!
Apparently the file that I created the script was corrupted, when I create a new file the code runs properly.

Opening SAP Logon Pad with VBA for any windows user profile

Private Sub CommandButton1_Click()
Unload LOGINZGLOC
Dim strPath As String
strPath = Environ("USERPROFILE") & "\Desktop\saplgpad.lnk"
Shell "strPath", 4
Set WshShell = CreateObject("WScript.Shell")
Do Until WshShell.AppActivate("SAP Logon Pad")
Application.Wait Now + TimeValue("0:00:01")
Loop
Dim Row
Dim UD As Worksheet
Set UD = Application.ActiveSheet
Row = 3
Set SapGui = GetObject("SAPGUI")
Set Appl = SapGui.GetScriptingEngine
Set Connection = Appl.Openconnection("[GT] ECC Production (GE4)", True)
Set session = Connection.Children(0)
This is the code I use for opening SAP using login info got from a userform. But since this is a code that's meant to be used by several employees and working colleagues, I need to open SAP on any user profile, for that I tried creating a shortcut and referencing to him on Desktop, since I'm new to VBA the code might look a little raw. The code fails, saying that the file couldn't be found.

Loop not opening PDFs...so copy/Paste to Excel fails (I think)

Apologies in advance for the length of this post, but I wanted to describe my issues in detail in the hopes one of you VBA masters can assist
Goal
Loop through all PDFs in a folder
For each PDF:select all/copy/paste into Excel
Call a separate macro to convert the pasted data into something
legible.
Background
The below sub [CopyPDFtoExcel()] worked yesterday but is now failing on the ActiveSheet.Paste line with the
"Runtime error '1004' Paste method of Worksheet class failed".
If I step though (via F8), it appears to NOT be actually opening the PDF, and therefor is unable to select all/copy/paste, producing the Runtime error. However, I do not get an error dialog, which I would think I would get (from the Debug.Assert False) if it can't find the file.
My fName's are defined as variable via a named range called path2008. These file paths were derived by running PullFilePathsforPDFs(), which spits out the full file path for each PDF in my folder. Then, I have selected those file paths and given it a name, in this case path2008, which is for 13 different PDFs. NOTE: There are actually 250+ PDFs in this folder but I selected a subset for testing, hence the 13 associated with path2008.
What I have done so far
Tested the file path for each PDF in the path2008 range by using the
(cumbersome non-looping) ActiveWorkbook.FollowHyperlink method,
which successfully opens all the PDFs. So, I'm pretty confident the
file paths are correct.
'ActiveWorkbook.FollowHyperlink "file path here"
Stripped out the select all/copy/paste VBA code, leaving just the
loop [See the sub TroubleshootingOpeningPDFLoop()]. When I step
through the FIRST time the yellow line goes from the Set oPDDoc =
oAVDoc.GetPDDoc line to the End If....presumabley meaning it found a
file during the first loop (though I do not see the PDF open). On
the SECOND (and all subsequent loops) it goes to Else then
Debug.Assert False (but no error dialog appears).
Restarted Excel and Acrobat, same issue
Restarted computer, same issue
Recreated a new workbook, same issue
Main code
Sub CopyPDFtoExcel()
Dim fName As Variant
Dim wbPayroll As Excel.Workbook
Dim wsConvert As Excel.Worksheet
Dim oPDFApp As AcroApp
Dim oAVDoc As AcroAVDoc
Dim oPDDoc As AcroPDDoc
Set wbPayroll = Workbooks("Payroll.xlsm")
Set wsConvert= wbPayroll.Sheets("Convert")
Set oPDFApp = CreateObject("AcroExch.App")
Set oAVDoc = CreateObject("AcroExch.AVDoc")
Set oPDDoc = CreateObject("AcroExch.PDDoc")
'Open the PDF file. The AcroAVDoc.Open function returns a true/false
For Each fName In Range("path2008")
If oAVDoc.Open(fName.Text, "") = True Then
Set oPDDoc = oAVDoc.GetPDDoc
Else
Debug.Assert False
End If
'Copy all using Acrobat menu
oPDFApp.MenuItemExecute ("SelectAll")
oPDFApp.MenuItemExecute ("Copy")
'Paste into Convert sheet
wbPayroll.Activate
wsConvert.Cells(1, 1).Select
ActiveSheet.Paste 'It worked yesterday, but now error on this line with below error
'Runtime error '1004' Paste method of Worksheet class failed
oAVDoc.Close (1) '(1)=Do not save changes
'oPDDoc.Close
Call ConversionMacro
Next
'Clean up
Set wbTransfer = Nothing
Set wsNew = Nothing
Set oPDFApp = Nothing
Set oAVDoc = Nothing
Set oPDDoc = Nothing
End Sub
My effort to isolate the PDF open failure problem
Sub TroubleshootingOpeningPDFLoop()
Dim fName As Variant
Dim wbPayroll As Excel.Workbook
Dim wsConvert As Excel.Worksheet
Dim oPDFApp As AcroApp
Dim oAVDoc As AcroAVDoc
Dim oPDDoc As AcroPDDoc
'Define your spreadsheet
Set wbPayroll = Workbooks("Payroll.xlsm")
Set wsConvert= wbPayroll.Sheets("Convert")
'Instantiate Acrobat Objects
Set oPDFApp = CreateObject("AcroExch.App")
Set oAVDoc = CreateObject("AcroExch.AVDoc")
Set oPDDoc = CreateObject("AcroExch.PDDoc")
'Open the PDF file. The AcroAVDoc.Open function returns a true/false
For Each fName In Range("path2008")
If oAVDoc.Open(fName.Text, "") = True Then
Set oPDDoc = oAVDoc.GetPDDoc
Else
Debug.Assert False
End If
Next
End Sub
Sub used to pull the file paths
Sub PullFilePathsforPDFs()
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim i As Long
Set objFSO = CreateObject("Scripting.FileSystemObject")
'Get the folder object
Set objFolder = objFSO.GetFolder("D:\Stuff\MoreStuff") 'all PDFs I need are stored here
i = 1
For Each objFile In objFolder.Files
Cells(i + 1, 1) = objFile.Name
Cells(i + 1, 2) = objFile.Path
i = i + 1
Next objFile
End Sub
I am having cut/copy - paste troubles lately (runtime error 1004)
Using the latest Excel but also working on "ancient" applications.
What did the trick for me was working with the original "given" name
(Sheet1,Sheet2 etc. As soon as I added/renamed the same sheets, the runtime errors came back.
If you want to make sure to generate an error when the opening operation does not succeed, I would add the following at the end of TroubleshootingOpeningPDFLoop:
If oPDDoc is nothing then
Debug.Assert False
End If
If this doesn't return an error, that means that the file is open in the application, but that it is not visible. It could be caused by the fact that you are using a PDDoc instead of an AVDoc. So, switching the 2 might allow you to see it when debugging.
As of your main problem, it might be due to the fact that Acrobat does not process the commands fast enough and you need to include some waiting time in your code to let Acrobat enough time to process the command. For example, you could have:
'Copy all using Acrobat menu
oPDFApp.MenuItemExecute ("SelectAll")
Application.Wait TimeSerial(Hour(Now()), Minute(Now()), Second(Now()) + 1)
oPDFApp.MenuItemExecute ("Copy")
Which will make VBA wait one second before running the next command.

Access VBA: working with an existing excel workbook (Run-Time error 9, if file is already open)

I'm writing a macro in Access that (hopefully) will:
create an Excel worksheet
set up and format it based on information in the Access database
after user input, will feed entered data into an existing Excel master file
Opening the blank sheet etc. is working absolutely fine, but I'm stuck trying to set the existing master file up as a variable:
Sub XLData_EnterSurvey()
Dim appXL As Excel.Application
Dim wbXLnew, wbXLcore As Excel.Workbook
Dim wsXL As Excel.Worksheet
Dim wbXLname As String
Set appXL = CreateObject("Excel.Application")
appXL.Visible = True
wbXLname = "G:\[*full reference to file*].xlsm"
IsWBOpen = fnIsWBOpen(wbXLname)
'separate function (Boolean), using 'attempt to open file and lock it' method
'from Microsoft site.
If IsWBOpen = False Then
Set wbXLcore = appXL.Workbooks.Open(wbXLname, True, False)
'open file and set as variable.
ElseIf IsWBOpen = True Then
wbXLcore = appXL.Workbooks("ResultsOverall.xlsm") 'ERROR HERE.
'file is already open, so just set as variable.
End If
Debug.Print wbXLcore.Name
Debug.Print IsWBOpen
Set appXL = Nothing
End Sub
When the file is closed, this works perfectly. However, when it's open I get:
Run-Time error '9':
Subscript out of range
I'm only just starting to teach myself VBA (very trial and error!) and nothing else I've seen in answers here / Google quite seems to fit the problem, so I'm a bit lost...
Considering that it works fine when the file is closed, I suspect I've just made some silly error in referring to the file - perhaps something to do with the 'createobject' bit and different excel instances??
Any suggestions would be much appreciated! Thanks
Thank you #StevenWalker
Here's the working code:
Sub XLData_EnterSurvey()
Dim appXL As Excel.Application
Dim wbXLnew As Excel.Workbook, wbXLcore As Excel.Workbook
Dim wsXL As Excel.Worksheet
On Error GoTo Handler
Set appXL = GetObject(, "Excel.Application")
appXL.Visible = True
Dim wbXLname As String
wbXLname = "G:\ [...] .xlsm"
IsWBOpen = fnIsWBOpen(wbXLname)
If IsWBOpen = False Then
Set wbXLcore = appXL.Workbooks.Open(wbXLname, True, False)
ElseIf IsWBOpen = True Then
Set wbXLcore = appXL.Workbooks("ResultsOverall.xlsm")
End If
Set appXL = Nothing
'-------------------Error handling------------------
Exit Sub
' For if excel is not yet open.
Handler:
Set appXL = CreateObject("Excel.Application")
Err.Clear
Resume Next
End Sub
Sorry I'm on my phone so I can't go in to too much detail or do much with the code but at a glance I think you might need to add an error handler so that if the file is already open, a different line of code is executed.
Add 'On error go to handler' (before creating the excel object) and at the bottom
Of your code add 'handler:'. In the error handler, use get object rather than create object.
You will have to ensure you use exit sub before the error handler or it will run the handler every time you run the code.
You can see an example of what I mean here: How to insert chart or graph into body of Outlook mail
Although please note in this example it's the other way round (if error 'getting' outlook, then create it).
Example in link:
Set myOutlook = GetObject(, "Outlook.Application")
Set myMessage = myOutlook.CreateItem(olMailItem)
rest of code here
Exit Sub
'If Outlook is not open, open it
Handler:
Set myOutlook = CreateObject("Outlook.Application")
Err.Clear
Resume Next
End sub
If you move the appXL.Workbooks statement to the debugging window, you will find that the names of the items in that collection are without extension.
So in your case, I'm guessing the line should read:
wbXLcore = appXL.Workbooks("ResultsOverall")

Reuse already open Excel Worksheet from Outlook

I am importing data from Outlook. The code for opening Excel opens an instance where personal.xlsb is not loaded, and will open multiple instances of Excel. If I run it twice it will open two instances but will overwrite the data in the first instance, leaving the second instance with a blank workbook. If Excel is closed and Outlook is not, then the code is run it will give an error since it won't put the data into the new "second" instance, even though only one instance is running.
Sub Extract()
On Error GoTo 0
Set myOlApp = Outlook.Application
Set mynamespace = myOlApp.GetNamespace("mapi")
Dim ThermoMail As Outlook.MailItem
Set ThermoMail = Application.ActiveInspector.CurrentItem
Set xlobj = CreateObject("excel.application")
xlobj.Visible = True
xlobj.Workbooks.Add
'Set Headings
Dim msgText, delimtedMessage, Delim1 As String
delimtedMessage = ThermoMail.Body
'Remove everything before "Lead Source:" and after "ELMS"
TrimmedArray = Split(delimtedMessage, "Source:")
delimtedMessage = TrimmedArray(1)
TrimmedArray = Split(delimtedMessage, "ELMS")
delimtedMessage = TrimmedArray(0)
'Split the array at each return
messageArray = Split(delimtedMessage, vbCrLf)
'this next line gives the error if excel is closed and the macro is rerun.
Range("A1:A" & UBound(messageArray) + 1) = WorksheetFunction.Transpose(messageArray)
Call splitAtColons
End Sub
Right now, you are creating a new instance of Excel with this line:
Set xlobj = CreateObject("excel.application")
Excel is different than some (most) Office Applications, because it can run multiple instances (PowerPoint, Outlook, Word cannot do this...)
So what you want to do is first check if there is an open instance of Excel, and use that. Only create a new instance if there is no instance already open.
On Error Resume Next
Set xlObj = GetObject(, "Excel.Application")
On Error GoTo 0
If xlObj Is Nothing Then Set xlObj = CreateObject("Excel.Application")

Resources