I use SAP at work and automate various tasks via the scripting interface using Excel/VBA and VBScript. I ran into a problem with a VBScript program I was working on that looked just like older VBScript programs that worked.
With multiple SAP sessions open, here's a simple script that works when executed by drag and drop onto one of the sessions. Note all the declarations are commented out so the objects are "created" when the script executes the SET statements.
Code: Select all
'Option Explicit
'Dim SapGuiAuto, application, connection, session, WScript
main
sub main
OPEN_SESSION
end sub
sub OPEN_SESSION
'Dim SapGuiAuto, application, connection, session, WScript
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 session.findById("wnd[0]/titl").text
end sub
If any of the other methods of declaring the objects are used, by uncommenting the lines commented out above, the session links to the first session opened, not the drop target.
Here's an example that fails:
Code: Select all
Option Explicit
'Dim SapGuiAuto, application, connection, session, WScript
main
sub main
OPEN_SESSION
end sub
sub OPEN_SESSION
Dim SapGuiAuto, application, connection, session, WScript
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 session.findById("wnd[0]/titl").text
end sub
So my question is why does declaring the object variables, either globally or locally, change the session the code links to?