title: VBA SAP createsession
body: <p>Maybe someone can help me with creating new SAP session using VBA Excel</p>
  
  <p>Some code to understand the problem </p>
  
  <pre><code>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
  </code></pre>
  
  <p>Most cases this one work fine. But sometimes this part doesn't work</p>
  
  <pre><code>Set session = Connection.Children(0)
  </code></pre>
  
  <p>it happens for example when SAP timeout occur (auto logoff after some idle time).
  In that case I have </p>
  
  <pre><code>sap.Connections.Count
  </code></pre>
  
  <p>= 2<br>
  but </p>
  
  <pre><code>Connection.Sessions.Count
  </code></pre>
  
  <p>= 0 <br> 
  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.<br> 
  <br> 
  What I want to do is to create new session. 
  I can do this by </p>
  
  <pre><code> Dim sapSession As SAPFEWSELib.GuiSession
   Dim sapCon As SAPFEWSELib.GuiConnection
   Set sapCon = sap.Connections.Item(0)
   Set sapSession = Connection.sessions.Item(0)
  
   sapsession.createsession
  </code></pre>
  
  <p>This  one works ok but it doesn't help couse I still need to set the session first <br> </p>
  
  <p>Is there a way to create session after setting the connection? <br> 
  Something like <code>sapCon.createsession</code>
  <br><br>
  And does anyone know how can I use specific session using variable? </p>
  
  <pre><code>Set sapSession = Connection.sessions.Item(0)
  </code></pre>
  
  <p>This works ok but when I try </p>
  
  <pre><code>Dim SessionNumber as integer 
  ....
  SessionNumber = 0 
  Set sapSession = Connection.sessions.Item(SessionNumber)
  </code></pre>
  
  <p>it throws an error "Bad index type for collection access" </p>