2
votes

Maybe someone can help me with creating new SAP session using VBA Excel

Some code to understand the problem

If Not IsObject(sap) Then
    Set SapGuiAuto = GetObject("SAPGUI")
    Set sap = SapGuiAuto.GetScriptingEngine
End If
If Not IsObject(Connection) Then
    Set Connection = sap.Connections.Item(0)
End If
If Not IsObject(session) Then
    Set session = Connection.Children(0)
End If

Most cases this one work fine. But sometimes this part doesn't work

Set session = Connection.Children(0)

it happens for example when SAP timeout occur (auto logoff after some idle time). In that case I have

sap.Connections.Count

= 2
but

Connection.Sessions.Count

= 0
Looks like the timeouted connection still hangs somewhere in SAP. So when I try to connect to first session of first connection I got an error couse there is no session in first connection.

What I want to do is to create new session. I can do this by

 Dim sapSession As SAPFEWSELib.GuiSession
 Dim sapCon As SAPFEWSELib.GuiConnection
 Set sapCon = sap.Connections.Item(0)
 Set sapSession = Connection.sessions.Item(0)

 sapsession.createsession

This one works ok but it doesn't help couse I still need to set the session first

Is there a way to create session after setting the connection?
Something like sapCon.createsession

And does anyone know how can I use specific session using variable?

Set sapSession = Connection.sessions.Item(0)

This works ok but when I try

Dim SessionNumber as integer 
....
SessionNumber = 0 
Set sapSession = Connection.sessions.Item(SessionNumber)

it throws an error "Bad index type for collection access"

2

2 Answers

2
votes

Excel requires that the session number is an integer, so you can use the type conversion from Cint(). Strange that this is advised/required even when SessionNumber is defined as an integer.

Dim SessionNumber  
....
SessionNumber = 0 
Set sapSession = Connection.sessions.Item(Cint(SessionNumber))
0
votes

The CreateSession command executes quickly and returns to Excel, but SAP takes a while to finish opening the new session. Thus, you'll need to make your Excel code wait.

Here's an example:

Const ms as Double = 1.15740741E-08  ' one millisecond, in days = 1/(1000*24*60*60)

Dim sapCon As SAPFEWSELib.GuiConnection
Dim sapSession As SAPFEWSELib.GuiSession
Dim nSessions As Integer

Set sapCon = sap.Connections(0)
Set sapSession = sapCon.Sessions(0)

nSessions = sapCon.Sessions.Count

sapSession.createsession

Do
    Application.Wait (Now() + 500*ms)
    If sapCon.Sessions.Count > nSessions Then Exit Do
Loop

Set sapSession = sapCon.Sessions.Item(CInt(sapCon.Sessions.Count - 1))