VBA SAP 创建会话

VBA SAP createsession

也许有人可以帮助我使用 VBA Excel

创建新的 SAP 会话

理解问题的一些代码

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

大多数情况下这一个工作正常。但有时这部分不起作用

Set session = Connection.Children(0)

例如当 SAP 超时发生时(空闲时间后自动注销)。 在那种情况下,我有

sap.Connections.Count

= 2
但是

Connection.Sessions.Count

= 0
看起来超时的连接仍然挂在 SAP 的某个地方。因此,当我尝试连接到第一个连接的第一个会话时,出现错误,因为第一个连接中没有会话。

我想要做的是创建新会话。 我可以通过

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

 sapsession.createsession

这个工作正常,但没有帮助,因为我仍然需要先设置会话

有没有办法在设置连接后创建会话?
sapCon.createsession

有谁知道如何使用变量使用特定会话?

Set sapSession = Connection.sessions.Item(0)

这工作正常,但当我尝试时

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

它抛出错误 "Bad index type for collection access"

Excel要求会话号为整数,所以可以使用Cint()的类型转换。奇怪的是,即使 SessionNumber 被定义为整数,这也是 advised/required。

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

CreateSession 命令执行得很快 returns 到 Excel,但 SAP 需要一段时间才能完成打开新会话。因此,您需要让 Excel 代码等待。

这是一个例子:

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