Use one session for multiple sub calls

82 Views Asked by At

I'm using 2 modules which I now want to combine in one run, so I call both of the subs in my code. But each sub was created to run independently, so each sub is making a connection to SAP separately. When calling the subs, I always need to acknowledge the 'a scripts wants access to SAP GUI'.

When I grant the access the first time, I'm not able to use that access when calling the second module. Is it possible to be able to run multiple modules/subs using 1 session during the execution of the code?

I tried using a function at the beginning of the code, but I'm not able to make it work. Anyone an idea how to do it correctly? I'm still a novice, so a detailed explanation would be really helpful to learn it :)

This was my function, but I still need to connect each module separately to run the specific codes.

Function SAP_Connection() As Boolean

If Not IsObject(SAPGuiApp) Then
   Set SapGuiAuto = GetObject("SAPGUI")
   Set SAPGuiApp = SapGuiAuto.GetScriptingEngine
End If
If Not IsObject(Connection) Then
   Set Connection = SAPGuiApp.Children(0)
End If
If Not IsObject(Session) Then
   Set SAP_session = Connection.Children(0)
End If
If IsObject(WScript) Then
   WScript.ConnectObject Session, "on"
   WScript.ConnectObject SapApplication, "on"
End If

SAP_Connection = True


End Function
1

There are 1 best solutions below

0
Kurt On

First, I would put that portion of code at the beginning of each SAP sub that you have, instead of having it as an independent function and calling it.

Sub SAP_procedure1()
If Not IsObject(SAPGuiApp) Then
   Set SapGuiAuto = GetObject("SAPGUI")
   Set SAPGuiApp = SapGuiAuto.GetScriptingEngine
End If
If Not IsObject(Connection) Then
   Set Connection = SAPGuiApp.Children(0)
End If
If Not IsObject(Session) Then
   Set SAP_session = Connection.Children(0)
End If
If IsObject(WScript) Then
   WScript.ConnectObject Session, "on"
   WScript.ConnectObject SapApplication, "on"
End If

Session.findById("wnd[0]").maximize
Session.findById("wnd[0]/tbar[0]/okcd").Text = "FS10N"
' insert rest of code

Next, I would check your SAP Accessibility & Scripting settings. You are able to turn off the two settings you mentioned, being notified/granting access to SAP GUI connection. To do this, please go to SAP Easy Access User Menu -> Options -> Accessibility & Scripting -> Scripting -> Uncheck boxes for: "Notify when a script attaches to SAP GUI" and "Notify when a script opens a connection"

Please see the attached picture of the settings:

SAP Scripting Settings

Then combine the procedures as you wish. If they are two different procedures, one simple way to combine them would look like:

Sub a_combined()
Dim wbName As String:       wbName = ThisWorkbook.Name

Application.Run "'" & wbName & "'!SAP_procedure1"

Application.Run "'" & wbName & "'!SAP_procedure2"
    
End Sub