Skip to Content
Former Member
Jul 29, 2011 at 01:11 PM

Run GUI script more than once


Hi everyone,

until now I usually asked users to log - in into SAP first and then use some Excel macros to download /modify data in SAP.

I have now found a neat way of opening SAP by opening a SAP shortcut - which works like a charm. Unfortunately that Charm has a very limited life span - because you are only able to run the macro once. If I want to rerun the macro I receive a Runtimeerror 91: wscript.ConnectObject Session, "on" .

This is the code I am using:

Dim SapApplication, SapGuiAuto, Connection, Session, wscript As Object

Public System As String

Sub SAP_prepare_sapscript()
System = "PL1"
    Application.EnableCancelKey = xlDisabled
    PathStrg = "C:\Temp\"
    On Error Resume Next
    Shell ("C:\Program Files\SAP\FrontEnd\SAPgui\"sapshcut.exe " & PathStrg & System & ".sap")

    If Wait_for_Window("SAP Easy Access") = False Then GoTo giveUp 'Separate Macro which waits until SAP is open
    On Error GoTo 0

    If Not IsObject(SapApplication) Then
        On Error Resume Next
        Set SapGuiAuto = GetObject("SAPGUI")
        If Err.Number <> 0 Then
            MsgBox ("Not able to log in")
            NoSap = True
            GoTo giveUp
        End If
        Set SapApplication = SapGuiAuto.GetScriptingEngine
    End If
    If Not IsObject(Connection) Then
        Set Connection = SapApplication.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
    Application.ScreenUpdating = False

    If Err.Number <> 0 Then
        If Err.Number <> 91 Then
            If Err.Number <> 9 Then
                MsgBox ("There was an error running the Script")
                Sapok = False
                GoTo giveUp
            End If
        End If
    End If
    Application.WindowState = xlMaximized
End Sub

Sub run_Sap_Script()
        'here I am running my normal SAP commands like opening transactions....
        'log out of SAP     
End Sub

Any Idea what needs to be changed?

Thanks for your help


Edited by: Fettertiger on Jul 29, 2011 3:11 PM