Skip to Content
Technical Articles
Author's profile photo Stefan Schnell

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-------------------------------------------------------------------

Assigned Tags

      26 Comments
      You must be Logged on to comment or reply to a post.
      Author's profile photo Former Member
      Former Member

      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.

      If Not IsObject(application) Then
         Set SapGuiAuto  = GetObject("SAPGUI")
         Set application = SapGuiAuto.GetScriptingEngine
      End If
      If Not IsObject(connection) Then
         Set connection = application.Children(0)
      End If
      msgbox "Please select a session to run the script on", vbSystemModal
      set session = application.ActiveSession

       

      Author's profile photo Stefan Schnell
      Stefan Schnell
      Blog Post Author

      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.

      set WshShell = WScript.CreateObject("WScript.Shell")
      WshShell.SendKeys "&{TAB}"

      At the moment I don’t have the possibility to check this solution, so please let us know your result.

      Cheers
      Stefan

      Author's profile photo Former Member
      Former Member

      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.

      If Not IsObject(application) Then
         Set SapGuiAuto  = GetObject("SAPGUI")
         Set application = SapGuiAuto.GetScriptingEngine
      End If
      If Not IsObject(connection) Then
         Set connection = application.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 application, "on"
      End If
      
      msgbox "Please select a session to run the script on", vbSystemModal
      
      set WshShell = CreateObject("WScript.Shell")
      WshShell.SendKeys "&{TAB}"
      
      set session = application.ActiveSession

       

       

      Author's profile photo Former Member
      Former Member

       

      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.

      If Not IsObject(application) Then
         Set SapGuiAuto  = GetObject("SAPGUI")
         Set application = SapGuiAuto.GetScriptingEngine
      End If
      If Not IsObject(connection) Then
         Set connection = application.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 application, "on"
      End If
      
      msgbox "Please select a session to run the script on", vbSystemModal
      
      Set WScr = CreateObject("WScript.Shell") 
      
      sTitle = Application.Connections.Item(0).Sessions.Item(0).findById("wnd[0]").text
      
      WScr.AppActivate(""& sTitle &"")
      
      
      set session = application.ActiveSession
      Author's profile photo Stefan Schnell
      Stefan Schnell
      Blog Post Author

      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

      <html>
      
        <head>
      
          <title>Test</title>
      
          <HTA:APPLICATION 
            ID="Test" VERSION="0.01" APPLICATIONNAME="Test"
            SYSMENU="yes" MAXIMIZEBUTTON="yes" MINIMIZEBUTTON="yes"
            BORDER="thin" INNERBORDER="no" SCROLL="no" SINGLEINSTANCE="yes"
            WINDOWSTATE="normal" />
      
        </head>
      
        <script language="VBScript">
      
          Sub Test()
      
            If Not IsObject(application) Then
              Set SapGuiAuto  = GetObject("SAPGUI")
              Set app = SapGuiAuto.GetScriptingEngine
            End If
      
            If Not IsObject(connection) Then
              Set connection = app.Children(0)
            End If
      
            Set oAutoIt = CreateObject("AutoItX3.Control")
            If IsObject(oAutoIt) Then
      
              MsgBox "Please select a session to run the script on", vbSystemModal
      
              oAutoIt.Send "!{TAB}"
      
              Set session = app.ActiveSession
      
              MsgBox session.Info.Client
      
            End If
      
          End Sub
      
        </script>
      
        <body bgcolor="white">
          <input type="button" name="btnStart" id="btnStart" value="Start" onclick="Test">
        </body>
      
      </html>

       

      Author's profile photo Former Member
      Former Member

      Stefan,

      Thank you! This solves the problem.

      Author's profile photo Raakesh Ganesan Parthiban
      Raakesh Ganesan Parthiban

      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.

      Author's profile photo Stefan Schnell
      Stefan Schnell
      Blog Post Author

      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

      Author's profile photo Aleksandar D
      Aleksandar D

      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

      Author's profile photo Stefan Schnell
      Stefan Schnell

      Hello Aleksandar D,

      try the /n in front of your transaction code:

      session.findById(“wnd[0]/tbar[0]/okcd”).Text = “/nva05”

      This terminates the current transaction, and starts a new transaction.

      Or, if you want to open a new session, /o.

      Best regards
      Stefan

      Author's profile photo Aleksandar D
      Aleksandar D

      Thanks Stefan,

      it never sasses to amaze  me how only so little can do so much in scripting 🙂

      Aleks

       

      Author's profile photo Sandra Rossi
      Sandra Rossi

      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)

      Author's profile photo Søren Westergaard
      Søren Westergaard

      Hi

      Stefan Schnell

      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.

      Regards Søren
      Author's profile photo Stefan Schnell
      Stefan Schnell

      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.

      '-Begin-----------------------------------------------------------------
      
      '-Directives------------------------------------------------------------
      Option Explicit
      
      '-Sub Action------------------------------------------------------------
      Sub Action(con, ses)
      
        Dim objShell, RegEx, Matches, con_no, ses_no
      
        Set RegEx = New RegExp
        RegEx.Pattern = "[0-9]"
        Set Matches = RegEx.Execute(con)
        con_no = Matches(0).Value
        Set Matches = RegEx.Execute(ses)
        ses_no = Matches(0).Value
      
        Set objShell = Wscript.CreateObject("WScript.Shell")
        objShell.Run "YourScript.vbs " + con_no + " " + ses_no
      
      End Sub
      
      
      '-Function GetSession---------------------------------------------------
      Function GetSession(connection, TAC)
      
        Dim sessions, session, sessionInfo, j, i
      
        Set sessions = connection.Sessions()
        '-Loop over sessions--------------------------------------------------
        For Each session In sessions
          If session.Busy() = vbFalse Then
            Set sessionInfo = session.Info()
            If sessionInfo.Transaction() = TAC Then
              Set GetSession = session
            End If
          End If
        Next
      
      End Function
      
      '-Sub Main--------------------------------------------------------------
      Sub Main()
      
        Dim SapGuiAuto, app, connection, session
        Dim session_SE16, session_SE37, session_SE38
        Dim arr
      
        Set SapGuiAuto = GetObject("SAPGUI")
        If Not IsObject(SapGuiAuto) Then
          Exit Sub
        End If
      
        Set app = SapGuiAuto.GetScriptingEngine
        If Not IsObject(app) Then
          Exit Sub
        End If
      
        Set connection = app.Children(0)
        If Not IsObject(connection) Then
          Exit Sub
        End If
      
        If connection.DisabledByServer = True Then
          Exit Sub
        End If
      
        Set session = connection.Children(0)
        If Not IsObject(session) Then
          Exit Sub
        End If
      
        If session.Info.IsLowSpeedConnection = True Then
          Exit Sub
        End If
      
        session.findById("wnd[0]/tbar[0]/okcd").text = "/oSE16"
        session.findById("wnd[0]").sendVKey 0
        session.findById("wnd[0]/tbar[0]/okcd").text = "/oSE37"
        session.findById("wnd[0]").sendVKey 0
        session.findById("wnd[0]/tbar[0]/okcd").text = "/oSE38"
        session.findById("wnd[0]").sendVKey 0
      
        Set session_SE16 = GetSession(connection, "SE16")
        arr = Split(session_SE16.ID, "/")
        WScript.Sleep 500
        Action arr(2), arr(3)
      
        Set session_SE37 = GetSession(connection, "SE37")
        arr = Split(session_SE37.ID, "/")
        WScript.Sleep 500
        Action arr(2), arr(3)
      
        Set session_SE38 = GetSession(connection, "SE38")
        arr = Split(session_SE38.ID, "/")
        WScript.Sleep 500
        Action arr(2), arr(3)
      
      End Sub
      
      '-Main------------------------------------------------------------------
      Main()
      
      '-End-------------------------------------------------------------------

      In the independent script the connection and session number are arguments.

      '-Begin------------------------------------------------------------------
      
      Set Args = WScript.Arguments
      con = Args(0)
      ses = Args(1)
      
      Set SapGuiAuto = GetObject("SAPGUI")
      If Not IsObject(SapGuiAuto) Then
        WScript.Quit
      End If
      
      Set app = SapGuiAuto.GetScriptingEngine
      If Not IsObject(app) Then
        WScript.Quit
      End If
      
      Set connection = app.Children(CLng(con))
      If Not IsObject(connection) Then
        WScript.Quit
      End If
      
      If connection.DisabledByServer = True Then
        WScript.Quit
      End If
      
      Set session = connection.Children(CLng(ses))
      If Not IsObject(session) Then
        WScript.Quit
      End If
      
      If session.Info.IsLowSpeedConnection = True Then
        WScript.Quit
      End If
      
      MsgBox session.Info.Transaction()
      
      '-End--------------------------------------------------------------------

      Best regards
      Stefan

      Author's profile photo Ziv Markovich
      Ziv Markovich

      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

      Author's profile photo Stefan Schnell
      Stefan Schnell

      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

      Author's profile photo Leo Cheong
      Leo Cheong

      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

      Author's profile photo Stefan Schnell
      Stefan Schnell

      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

      Author's profile photo Leo Cheong
      Leo Cheong

      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.

      Author's profile photo Stefan Schnell
      Stefan Schnell

      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

      Author's profile photo Leo Cheong
      Leo Cheong

      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

      Author's profile photo Stefan Schnell
      Stefan Schnell

      Hello Leo,

      this should work.

      Best regards
      Stefan

      '-Begin-----------------------------------------------------------------
      
      '-Directives------------------------------------------------------------
      Option Explicit
      
      '-Sub Action------------------------------------------------------------
      Sub Action(session)
        'Insert your SAP GUI Scripting code from recorder here
      End Sub
      
      '-Function GetSession---------------------------------------------------
      Function GetSession(SID)
      
        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
      
        For Each connection In connections
          Set sessions = connection.Sessions()
          For Each session In sessions
            If session.Busy() = vbFalse Then
              Set sessionInfo = session.Info()
              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("Z2L")
        Action session
      
      End Sub
      
      '-Main------------------------------------------------------------------
      Main()
      
      '-End-------------------------------------------------------------------
      Author's profile photo Leo Cheong
      Leo Cheong

      Hi Stefan,

      Thank you very much.
      It is working perfectly now !!!

      Very much appreciate for your reply and work.

      Author's profile photo Kweku Essandoh
      Kweku Essandoh

      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

      Author's profile photo Stefan Schnell
      Stefan Schnell

      Kweku Essandoh

       

      Hello Kweku,
      try this approach.
      Best regards
      Stefan

      If Not IsObject(application) Then
        On Error Resume Next
        'If the script can't get the object, it starts saplogon and tries to get the object again.
        Set SapGuiAuto  = GetObject("SAPGUI")
        If Err.Number <> 0 Then
          On Error Goto 0
          Set WshShell = CreateObject("WScript.Shell")
          Set oExec = WshShell.Exec("c:\Program Files (x86)\SAP\FrontEnd\SAPgui\saplogon.exe")
          Do While Not WshShell.AppActivate("SAP Logon 770") 
            WScript.Sleep 500 
          Loop
          Set SapGuiAuto  = GetObject("SAPGUI")
        Else
          On Error Goto 0
        End If
        Set application = SapGuiAuto.GetScriptingEngine
      End If
      Author's profile photo Kweku Essandoh
      Kweku Essandoh

      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 😊

       

      Sub Man()
      
      
      Dim SapGui As Object
      
       On Error Resume Next
       
        Set SapGui = GetObject("SAPGUI")
      
        If Err.Number <> 0 Then
           Call SapConn
         Else
           Call code 'this is the code to run
        End If
      
      
      End Sub
      
      
      
      Sub SapConn()
      
      Dim Appl As Object
      Dim connection As Object
      Dim session As Object
      Dim sessions As Object
      Dim WshShell As Object
      Dim SapGui As Object
      
      
      
      
      
      'Of course change for your file directory
      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:01")
      Loop
      
      Set WshShell = Nothing
      
      Set SapGui = GetObject("SAPGUI")
      Set Appl = SapGui.GetScriptingEngine
      Set connection = Appl.OpenConnection("NEA Dow Prod - ERP Central Component (ECC) (SSO) (001)", True)
      Set session = connection.Children(0)
      
      'if You need to pass username and password
      session.FindById("wnd[0]/usr/txtRSYST-MANDT").Text = "900"
      session.FindById("wnd[0]/usr/txtRSYST-BNAME").Text = "user"
      session.FindById("wnd[0]/usr/pwdRSYST-BCODE").Text = "password"
      session.FindById("wnd[0]/usr/txtRSYST-LANGU").Text = "EN"
      
      
      'ACTION CODE---------------------------------------------------------------------------------------------------------------
      
        On Error Resume Next
      
        Call code 'main code to run 
      
        MsgBox ("EXTARCTION COMPLETE")
      
      End Sub