During my experience with SAP GUI Scripting I've noticed that among all the functions/procedures in any script one presents all the time, namely the function of creating Sap GUI Session. Which I think is the most usable object in SAP GUI Scripting API.
At first, I was not paying much attention to this function (was satisfied by standard, created by Script Recorder); but as the programs became more complicated necessity of handy function becomes obvious.
SapLogON function is quite simple: returns true if Session has been created and false if any error occurs; also, in case of true, public object Session is ready to use in other functions. Not a masterpiece, but much better than standard one :).
Function written for using in VBA Project.
'''----------------------------------------------------------
Public Session
Function SapLogON()
SapLogON = False
''Destroy old objects
Set SapGuiAuto = Nothing
Set Session = Nothing
'''-----------SAP-------------------------------------------
On Error Resume Next
Set SapGuiAuto = GetObject("SAPGUI")
On Error GoTo 0
If (SapGuiAuto Is Nothing) Then
MsgBox "Login to SAP for continue", vbExclamation, "Sap LogON"
Exit Function
End If
Set Gui_application = SapGuiAuto.getScriptingEngine
''CHeck if at least one connection open
If Gui_application.Connections.Count = 0 Then
MsgBox "Login to SAP for continue", vbExclamation, "Sap LogON"
Exit Function
End If
'--------------- Define Enviroment if several are opened------------
If Gui_application.Children.Count > 1 Then
''----Collect Env. names
env_descr = ""
For i = 0 To Gui_application.Children.Count - 1
env_descr = env_descr & i + 1 & " ->" & Gui_application.Connections(CInt(i)).Description & vbCrLf
Next i
env_sap = InputBox("Found several opened SAP enviroment, please select one to work with:" & vbCrLf & vbCrLf & env_descr, "SAP LogOn", "1")
''Check for correct values
env_sap = Val(env_sap)
If env_sap < 1 Or env_sap > Gui_application.Children.Count Then
MsgBox "You've chosen a wrong value, macro will be terminated!", vbCritical, "Sap LogON"
Exit Function
End If
'Define GuiConnection object
Set Connection = Gui_application.Connections(CInt(env_sap - 1))
Else
'Define GuiConnection object
Set Connection = Gui_application.Connections(0)
End If
''-----------------------------------------------------------------
'---------Check if a user have been logged
If Connection.Children(0).info.User = "" Then
MsgBox "Login to SAP for continue!", vbExclamation, "Sap LogON"
Exit Function
End If
'----------Define free session---------------
For i = 0 To Connection.Children.Count - 1
If Connection.Children(CInt(i)).Busy = False Then
Set Session = Connection.Children(CInt(i))
Exit For
End If
Next i
'if all session are busy
If (Session Is Nothing) Then
MsgBox "All sessions are busy !" & Chr(10) & "Please create a new one or terminate performance in the existing!", vbExclamation, "Sap LogON"
Exit Function
End If
SapLogON = True ''Success
End Function
Комментариев нет:
Отправить комментарий