Technical Articles
How to select a specific session to do SAP GUI Scripting activities inside it
Very often it is asked the question, how to select a specific session to do some SAP GUI Scripting activities inside it. The selection criterias are often the system ID (SID), a transaction code (TAC) or a program name. So I develop an example in VBScript resp. SAP GUI Scripting code, which offers these possibilities. It scans all connections with all sessions and select a specific session. The selection criterias in this example are properties of the session info object – here SID and TAC, but you can use what ever you want from the SAP GUI Scripting object hierarchy. If the SID is equal to NSP and the TAC is equal to SE80 the sub routine Action is called. In this sub routine you can store the part of your code from the SAP GUI Scripting recorder, which is below the object definition.
'-Begin-----------------------------------------------------------------
'-
'- Example to show how to select a specific session to do SAP GUI
'- Scripting activities inside it. It scans all connections with all
'- sessions to find the correct one.
'-
'- Author: Stefan Schnell
'-
'-----------------------------------------------------------------------
'-Directives------------------------------------------------------------
Option Explicit
'-Sub Action------------------------------------------------------------
'-
'- Get the selected session and do the action inside it
'-
'-----------------------------------------------------------------------
Sub Action(session)
'Insert your SAP GUI Scripting code from recorder here
MsgBox session.findById("wnd[0]/titl").text
End Sub
'-Function GetSession---------------------------------------------------
'-
'- Detects the session
'-
'-----------------------------------------------------------------------
Function GetSession(SID, TAC)
Dim SapGuiAuto, application, connections, connection, sessions
Dim session, sessionInfo, j, i
Set SapGuiAuto = GetObject("SAPGUI")
If Not IsObject(SapGuiAuto) Then
Exit Function
End If
Set application = SapGuiAuto.GetScriptingEngine
If Not IsObject(application) Then
Set SapGuiAuto = Nothing
Exit Function
End If
Set connections = application.Connections()
If Not IsObject(connections) Then
Set SapGuiAuto = Nothing
Set application = Nothing
Exit Function
End If
'-Loop over connections-----------------------------------------------
For Each connection In connections
Set sessions = connection.Sessions()
'-Loop over sessions------------------------------------------------
For Each session In sessions
If session.Busy() = vbFalse Then
'---------------------------------------------------------------
'-
'- With the session info object is it possible to select a
'- specific session which executes the activities. In our
'- example it is the system name and the transaction code, but
'- you can use all properties of the session info object.
'-
'---------------------------------------------------------------
Set sessionInfo = session.Info()
If sessionInfo.SystemName() = SID And _
sessionInfo.Transaction() = TAC Then
Set GetSession = session
End If
End If
Next
Next
End Function
'-Sub Main--------------------------------------------------------------
'-
'- Main procedure to select the session
'-
'-----------------------------------------------------------------------
Sub Main()
Dim session
Set session = GetSession("NSP", "SE80")
Action session
End Sub
'-Main------------------------------------------------------------------
Main()
'-End-------------------------------------------------------------------
Stefan,
I'm hoping you can help with a problem that is somewhat similar. I'm trying to be able to have a pop up box that prompts you to select the session you want to use the script on. Once you click on the session then you will hit OK and SAP will then know the session you would like to run the script on.
The code below works fine if I'm using a hotkey to launch the script.
The problem comes when I'm trying to launch the script using HTA. I get an error saying "Object required: 'session'".
How can I fix this? I need to be able to choose which sap session to run the script on while launching with HTA.
It seems that running via HTA causes additional problems because the HTA window will steal focus from SAP.
Hello JT,
I check your problem and as you say, the HTA window gets the focus, because you open a message box in the context of the HTA window and your last activity is to press the button of this message box, so the message box is in top of the window z-order and therewith the HTA window.
But you can try a tiny trick to solve your problem: Switch via SendKeys and Alt+Tab to the next window in the z-order, your SAP session, which is activated as the last before.
At the moment I don’t have the possibility to check this solution, so please let us know your result.
Cheers
Stefan
Stefan,
I get the error Object Required: "WScript". I did some googling and saw some results that said it won't work that way using HTA and I need to remove the Wscript from before CreateObject. However, now I'm getting the error Object Required: "Session". Below is the code that I last tried.
I also have tried a different approach and had some limited success. It would work for a couple of times to select the session that I clicked on, but then it would start defaulting back to the first session.
Please see the code below.
Hello JT,
here a working solution with AutoItX, which is part from AutoIt scripting language, SendKeys from WScript.Shell doesn’t work.
Your second solution doesn’t work, because you are using
Connections.Item(0).Sessions.Item(0)
which means Connection(0) and Session(0)
and this isn’t what you want.
Cheers
Stefan
Stefan,
Thank you! This solves the problem.
Hi Stefan,
can you help me with the below code to run the TCODE and take input from excel inputs.
Sub Create_Doc()
Dim SAPguiAPP As SAPFEWSELib.GuiApplication
Dim Connection As SAPFEWSELib.GuiConnection
Dim Session As SAPFEWSELib.GuiSession
Dim PartNumber, FileType, Revision, Description, LAB, Ecn, Authorization, AttachmentPath, AttachmentName As String
Dim i As Integer
PartNumber = Cells(2, 3).Value
FileType = Cells(2, 4).Value
Revision = Cells(2, 5).Value
Description = Cells(2, 6).Value
LAB = Cells(2, 7).Value
Ecn = Cells(2, 8).Value
Authorization = Cells(2, 9).Value
AttachmentPath = Cells(2, 11).Value
AttachmentName = Cells(2, 12).Value
i = 0
If SAPguiAPP Is Nothing Then
Set SapGuiAuto = GetObject("SAPGUI")
Set SAPguiAPP = SapGuiAuto.GetScriptingEngine
End If
If Connection Is Nothing Then
Set Connection = SAPguiAPP.Children(0)
End If
ses = 0
If Session Is Nothing Then
Set Session = Connection.Children(Int(ses))
End If
Session.FindById("wnd[0]").ResizeWorkingPane 215, 33, False
Session.FindById("wnd[0]/usr/txtRSYST-BNAME").Text = "503032981"
Session.FindById("wnd[0]/usr/pwdRSYST-BCODE").Text = "Start123"
Session.FindById("wnd[0]/usr/pwdRSYST-BCODE").SetFocus
Session.FindById("wnd[0]/usr/pwdRSYST-BCODE").CaretPosition = 8
Session.FindById("wnd[0]").SendVKey 0
Session.FindById("wnd[0]/tbar[0]/okcd").Text = "CV01N"
Session.FindById("wnd[0]").SendVKey 0
Session.FindById("wnd[0]/usr/ctxtDRAW-DOKNR").Text = PartNumber
Session.FindById("wnd[0]/usr/ctxtDRAW-DOKAR").Text = FileType
Session.FindById("wnd[0]/usr/ctxtDRAW-DOKTL").Text = "000"
Session.FindById("wnd[0]/usr/ctxtDRAW-DOKVR").Text = Revision
Session.FindById("wnd[0]/usr/ctxtDRAW-DOKVR").SetFocus
Session.FindById("wnd[0]/usr/ctxtDRAW-DOKVR").CaretPosition = 2
Session.FindById("wnd[0]").SendVKey 0
Session.FindById("wnd[0]/usr/tabsTAB_MAIN/tabpTSMAIN/ssubSCR_MAIN:SAPLCV110:0102/txtDRAT-DKTXT").Text = Description
Session.FindById("wnd[0]/usr/tabsTAB_MAIN/tabpTSMAIN/ssubSCR_MAIN:SAPLCV110:0102/ctxtDRAW-LABOR").Text = LAB
Session.FindById("wnd[0]/usr/tabsTAB_MAIN/tabpTSMAIN/ssubSCR_MAIN:SAPLCV110:0102/ctxtDRAW-AENNR").Text = Ecn
Session.FindById("wnd[0]/usr/tabsTAB_MAIN/tabpTSMAIN/ssubSCR_MAIN:SAPLCV110:0102/ctxtDRAW-BEGRU").Text = Authorization
Session.FindById("wnd[0]/usr/tabsTAB_MAIN/tabpTSMAIN/ssubSCR_MAIN:SAPLCV110:0102/ctxtDRAW-BEGRU").SetFocus
Session.FindById("wnd[0]/usr/tabsTAB_MAIN/tabpTSMAIN/ssubSCR_MAIN:SAPLCV110:0102/ctxtDRAW-BEGRU").CaretPosition = 4
Session.FindById("wnd[0]/usr/tabsTAB_MAIN/tabpTSMAIN/ssubSCR_MAIN:SAPLCV110:0102/btnPB_FILE_BROWSER").Press
Session.FindById("wnd[1]/usr/ctxtDY_PATH").Text = AttachmentPath
Session.FindById("wnd[1]/usr/ctxtDY_FILENAME").Text = AttachmentName
Session.FindById("wnd[1]/usr/ctxtDY_FILENAME").CaretPosition = 15
Session.FindById("wnd[1]").SendVKey 0
End Sub
the above coding worked for couple of times but after that, When i try to run the above code it displays a error in first line (Dim SAPguiAPP As SAPFEWSELib.GuiApplication) as " User-defined type not defined"
Please, help me.
Hello Raakesh,
thanks for your comment.
It is necessary to bind sapfewse.ocx in your VBA project via menu Extras and References.
You can find sapfewse.ocx in the directory C:\Program Files (x86)\SAP\FrontEnd\SAPgui.
Cheers
Stefan
HI Stefan,
Hope you are doing ok,
I'm having trouble with my code as it will not run if the fist SAP connection is not on the home tab.
I have tried multiple ways to start a new session form an existing one but with no luck
Sub SapData()
Dim dFrom, dTo, soldTo As String
soldTo = Worksheets("Welcome").Range("H2").Value
dFrom = Worksheets("Welcome").Range("H3").Value
dTo = Worksheets("Welcome").Range("H4").Value
If Not IsObject(GUIapplication) Then
Set SapGuiAuto = GetObject("SAPGUI")
Set GUIapplication = SapGuiAuto.GetScriptingEngine
End If
If Not IsObject(Connection) Then
Set Connection = GUIapplication.Children(0)
End If
If Not IsObject(session) Then
Set session = Connection.Children(0)
End If
If IsObject(WScript) Then
WScript.ConnectObject session, "on"
WScript.ConnectObject GUIapplication, "on"
End If
session.findById("wnd[0]").maximize
session.findById("wnd[0]/tbar[0]/okcd").Text = "va05"
session.findById("wnd[0]").sendVKey 0
session.findById("wnd[0]/usr/ctxtVBCOM-KUNDE").Text = "10364323"
session.findById("wnd[0]/tbar[1]/btn[33]").press
session.findById("wnd[1]/usr/ctxtVBCOM-VKORG").Text = "3100"
session.findById("wnd[1]/usr/ctxtVBCOM-VTWEG").Text = "20"
session.findById("wnd[1]/usr/ctxtVBCOM-SPART").Text = "10"
session.findById("wnd[1]/usr/ctxtVBCOM-SPART").SetFocus
session.findById("wnd[1]/usr/ctxtVBCOM-SPART").caretPosition = 2
session.findById("wnd[1]/tbar[0]/btn[0]").press
'session.findById("wnd[0]/usr/ctxtVBCOM-AUDAT").Text = "15.05.2020"
'session.findById("wnd[0]/usr/ctxtVBCOM-AUDAT_BIS").Text = "14.06.2020"
session.findById("wnd[0]/usr/radVBCOM-VBALL").SetFocus
session.findById("wnd[0]/tbar[1]/btn[44]").press
session.findById("wnd[1]/tbar[0]/btn[29]").press
session.findById("wnd[2]/usr/tblSAPLSKBHTC_FIELD_LIST_820").verticalScrollbar.Position = 12
session.findById("wnd[2]/usr/tblSAPLSKBHTC_FIELD_LIST_820").getAbsoluteRow(12).Selected = True
session.findById("wnd[2]/usr/tblSAPLSKBHTC_FIELD_LIST_820/txtGT_FIELD_LIST-SELTEXT[0,0]").SetFocus
session.findById("wnd[2]/usr/tblSAPLSKBHTC_FIELD_LIST_820/txtGT_FIELD_LIST-SELTEXT[0,0]").caretPosition = 0
session.findById("wnd[2]/usr/btnAPP_FL_SING").press
session.findById("wnd[2]/usr/btnAPP_WL_SING").press
session.findById("wnd[2]/tbar[0]/btn[0]").press
session.findById("wnd[2]/usr/ssub%_SUBSCREEN_FREESEL:SAPLSSEL:1105/ctxt%%DYN001-LOW").Text = "DARVOSH_A700"
session.findById("wnd[2]/usr/ssub%_SUBSCREEN_FREESEL:SAPLSSEL:1105/ctxt%%DYN001-LOW").caretPosition = 12
session.findById("wnd[2]/tbar[0]/btn[0]").press
session.findById("wnd[1]/usr/lbl[1,15]").SetFocus
session.findById("wnd[1]/usr/lbl[1,15]").caretPosition = 3
session.findById("wnd[1]").sendVKey 2
session.findById("wnd[0]/tbar[0]/btn[0]").press
session.findById("wnd[0]/usr/cntlGRID1/shellcont/shell/shellcont[1]/shell").currentCellRow = -1
session.findById("wnd[0]/usr/cntlGRID1/shellcont/shell/shellcont[1]/shell").selectColumn "ZZVDATU2"
session.findById("wnd[0]/tbar[1]/btn[38]").press
session.findById("wnd[1]/usr/ssub%_SUBSCREEN_FREESEL:SAPLSSEL:1105/ctxt%%DYN001-LOW").Text = dFrom
session.findById("wnd[1]/usr/ssub%_SUBSCREEN_FREESEL:SAPLSSEL:1105/ctxt%%DYN001-HIGH").Text = dTo
session.findById("wnd[1]/usr/ssub%_SUBSCREEN_FREESEL:SAPLSSEL:1105/ctxt%%DYN001-HIGH").SetFocus
session.findById("wnd[1]/usr/ssub%_SUBSCREEN_FREESEL:SAPLSSEL:1105/ctxt%%DYN001-HIGH").caretPosition = 10
session.findById("wnd[1]/tbar[0]/btn[0]").press
session.findById("wnd[0]/usr/cntlGRID1/shellcont/shell/shellcont[1]/shell").setCurrentCell -1, "ZZMVGR1"
session.findById("wnd[0]/usr/cntlGRID1/shellcont/shell/shellcont[1]/shell").selectColumn "ZZMVGR1"
session.findById("wnd[0]/tbar[1]/btn[38]").press
End Sub
Hello Aleksandar D,
try the /n in front of your transaction code:
This terminates the current transaction, and starts a new transaction.
Or, if you want to open a new session, /o.
Best regards
Stefan
Thanks Stefan,
it never sasses to amaze me how only so little can do so much in scripting 🙂
Aleks
In fact /N is not part of scripting, it's part of SAP GUI, long before scripting was introduced. For more information see 26171 - Possible entry values for command field (OK-code)
Hi
I'm relative new to SAP Scripting. I wonder if you can help me with your script. I want to run your script with the SAP code in three windows: T-code: COOIS, MB51 and MB52. So when I run the script it will find the windows and run the codes in each window. Hope you can help.
Søren West
Hello Søren,
welcome in the world of SAP GUI Scripting. Sure can I help you, as attachment two scripts.
The first script starts three different transaction codes in three new sessions. Then it starts an independent script, with the connection and session number as arguments. Here you can also start, dependently from your transaction code, different scripts. On this way you achieve parallelism.
In the independent script the connection and session number are arguments.
Best regards
Stefan
Hello Stefan,
Is there a way to select active session in gui scripting when there are multiple modes which include the same transaction ?
thanks
Ziv
Hello Ziv,
in my opinion yes. Loop over the sessions and store the information in an array. Sort the array, e.g. with bubblesort, and find the double entries.
Best regards
Stefan
Hi Stefan,
I am very new to SAP scripting.
Appreciate if you could help me out on this.
I was running your script, however it got the error below.
What can I do about it ?
Run Time Error 13, Type Mismatch for below bolded line
What could be the error ?
Dim session
Set session = GetSession("Z2L", "SE16")
Action session
End Sub
Hello Leo,
it seems that your double quotes are not correct.
Set session = GetSession(“Z2L”, “SE16”)
Set session = GetSession("Z2L", "SE16")
Use Ascii 34 as double quote.
Best regards
Stefan
Hi Stefan,
Thanks for highlghting that.
I have a question on this script.
As it would choose the SID and TAC that currently running.
Is that possible for it to choose the selected SID only but not TAC ?
So that any sessions of the SID will be choosen to run the script but not on specific TAC
Thanks in advance.
Leo Cheong
Hello Leo,
sure is that possible. You can find an approach on top of this messages. Delete the code sequences for the TAC and use SID only.
Best regards
Stefan
Dear Stefan,
I`m sorry, I don't quite get that.
Could you help me point out which area I should remove ? So that only SID is being screened before attached the connection.
Below is my code.
Much appreciate with your help.
Option Explicit
'-Sub Action
'- Get the selected session and do the action inside it
Sub Action(session)
'Insert your SAP GUI Scripting code from recorder here
Const fpath = "C:\Users"
Const ffilename = "Weekly.txt"
'Insert your SAP GUI Scripting code from recorder here
session.findById("wnd[0]").Maximize
session.findById("wnd[0]/tbar[0]/okcd").Text = "/nUDM_SPECIALIST"
session.findById("wnd[0]/tbar[0]/btn[0]").press
session.findById("wnd[0]/usr/cntlGO_BUTTON_CONT/shellcont/shell").pressContextButton "CONT"
session.findById("wnd[0]/usr/cntlGO_BUTTON_CONT/shellcont/shell").selectContextMenuItem "OSPWL"
session.findById("wnd[1]/usr/radP_OW").Select
session.findById("wnd[1]/usr/ctxtCOLLGRP-LOW").Text = "AP-COL1"
session.findById("wnd[1]/tbar[0]/btn[8]").press
session.findById("wnd[1]/usr/txtG_ENTRIES").Text = ""
session.findById("wnd[1]/usr/txtG_ENTRIES").caretPosition = 0
session.findById("wnd[1]/tbar[0]/btn[0]").press
session.findById("wnd[0]/usr/cntlLC_WORKLIST/shellcont/shell/shellcont[0]/shell").pressToolbarContextButton "&MB_VARIANT"
session.findById("wnd[0]/usr/cntlLC_WORKLIST/shellcont/shell/shellcont[0]/shell").selectContextMenuItem "&LOAD"
session.findById("wnd[1]/usr/ssubD0500_SUBSCREEN:SAPLSLVC_DIALOG:0501/cntlG51_CONTAINER/shellcont/shell").setCurrentCell 55, "TEXT"
session.findById("wnd[1]/usr/ssubD0500_SUBSCREEN:SAPLSLVC_DIALOG:0501/cntlG51_CONTAINER/shellcont/shell").selectedRows = "55"
session.findById("wnd[1]/usr/ssubD0500_SUBSCREEN:SAPLSLVC_DIALOG:0501/cntlG51_CONTAINER/shellcont/shell").clickCurrentCell
session.findById("wnd[0]/usr/cntlLC_WORKLIST/shellcont/shell/shellcont[0]/shell").pressToolbarContextButton "&MB_EXPORT"
session.findById("wnd[0]/usr/cntlLC_WORKLIST/shellcont/shell/shellcont[0]/shell").selectContextMenuItem "&PC"
session.findById("wnd[1]/usr/subSUBSCREEN_STEPLOOP:SAPLSPO5:0150/sub:SAPLSPO5:0150/radSPOPLI-SELFLAG[1,0]").Select
session.findById("wnd[1]/usr/subSUBSCREEN_STEPLOOP:SAPLSPO5:0150/sub:SAPLSPO5:0150/radSPOPLI-SELFLAG[1,0]").SetFocus
session.findById("wnd[1]/tbar[0]/btn[0]").press
session.findById("wnd[1]/usr/ctxtDY_PATH").Text = fpath
session.findById("wnd[1]/usr/ctxtDY_FILENAME").Text = ffilename
session.findById("wnd[1]/usr/ctxtDY_FILE_ENCODING").Text = "4103"
session.findById("wnd[1]/usr/ctxtDY_FILE_ENCODING").SetFocus
session.findById("wnd[1]/usr/ctxtDY_FILE_ENCODING").caretPosition = 4
session.findById("wnd[1]/tbar[0]/btn[11]").press
End Sub
'-Function GetSession
'- Detects the session
Function GetSession(SID, TAC)
Dim SapGuiAuto, application, connections, connection, sessions
Dim session, sessionInfo, j, i
Set SapGuiAuto = GetObject("SAPGUI")
If Not IsObject(SapGuiAuto) Then
Exit Function
End If
Set application = SapGuiAuto.GetScriptingEngine
If Not IsObject(application) Then
Set SapGuiAuto = Nothing
Exit Function
End If
Set connections = application.connections()
If Not IsObject(connections) Then
Set SapGuiAuto = Nothing
Set application = Nothing
Exit Function
End If
End Function
'-Sub Main
'- Main procedure to select the session
Sub Main()
Dim session
Set session = GetSession("Z2L", "SE16")
Action session
End Sub
Hello Leo,
this should work.
Best regards
Stefan
Hi Stefan,
Thank you very much.
It is working perfectly now !!!
Very much appreciate for your reply and work.
Hi Stefan,
I am looking to do similar but would like to first check if SAP is open, if its not, would like to open it from a stored location. If session is already open I would like to open a new session and run the code in the opened session .
How do I o about this ?
I keep getting errors from the code below
'-Directives------------------------------------------------------------
Option Explicit
'-Sub Action------------------------------------------------------------
Sub Action(session)
'insert script
End Sub
'-Function GetSession---------------------------------------------------
Function GetSession(SID)
Dim SapGuiAuto, applications, connections, connection, sessions
Dim session, sessionInfo, j, i
Dim WshShell
Shell "C:\Program Files (x86)\SAP\FrontEnd\SAPgui\saplogon.exe", 4
Set WshShell = CreateObject("WScript.Shell")
Do Until WshShell.AppActivate("SAP Logon ")
application.Wait Now + TimeValue("0:00:05")
Loop
Set WshShell = Nothing
Set SapGuiAuto = GetObject("SAPGUI")
If Not IsObject(SapGuiAuto) Then
Exit Function
End If
Set applications = SapGuiAuto.GetScriptingEngine
If Not IsObject(applications) Then
Set SapGuiAuto = Nothing
Exit Function
End If
Set connections = applications.OpenConnection("NEA Dow Prod - ERP Central Component (ECC) (SSO) (001)", True)
'Set connections = applications.connections()
If Not IsObject(connections) Then
Set SapGuiAuto = Nothing
Set applications = Nothing
Exit Function
End If
For Each connection In connections
Set sessions = connection.sessions()
For Each session In sessions
If session.Busy() = vbFalse Then
'session.FindById("wnd[0]/tbar[0]/okcd").Text = "/oIW23"
Set sessionInfo = session.Info() 'takes info of the session
If sessionInfo.SystemName() = SID Then
Set GetSession = session
Exit Function
End If
End If
Next
Next
End Function
'-Sub Main--------------------------------------------------------------
Sub Main()
Dim session
Set session = GetSession("PRD")
Action session
End Sub
Kweku Essandoh
Hello Kweku,
try this approach.
Best regards
Stefan
Hello Stefan,
I kept getting an error after adding the code so I decided to use the call function to call Sapconn.
Thanks for your help much appreciated 😊