VBA Sap脚本可打开或连接/保留在已打开的会话窗口中

时间:2019-04-17 17:37:39

标签: excel vba scripting sap sap-gui

我可以通过使用VBA和SAP记录并播放.vbs脚本来自动化SAP事务数据检索,现在,如果SAP Easy,我现在遇到的问题是我在Visual Basic Studio .NET的同一程序中没有看到访问我的名字连接:LA-6-Prod已经打开,然后出现Multilogon窗口并破坏了我的代码,从而使整个操作失败。

如何获取我的代码以使用现有的打开的连接,或者在未打开的情况下打开它?

如果LA-6-Prod未打开,但无法告诉最终用户在执行宏之前确保未打开任何连接窗口,这是完美的选择。

非常感谢您

这是我的代码:

  Sub my_sap

  Dim SapGui

  Dim Applic

  Dim connection

  strconnection = Worksheets("sap_info").Range("A2").Value

  Dim session

  Dim WSHShell

  Shell "C:\Program Files (x86)\SAP\FrontEnd\SAPgui\saplogon.exe", vbNormalFocus

  Set WSHShell = CreateObject("WScript.Shell")

  Do Until WSHShell.AppActivate("SAP Logon ")

    application.Wait Now + TimeValue("0:00:01")

  Loop

  Set WSHShell = Nothing

  Set SapGui = GetObject("SAPGUI")

  Set Applic = SapGui.GetScriptingEngine

  Set connection = Applic.OpenConnection('LA-6-Prod', True)

  Set session = connection.Children(0)

'===============SAP SCRIPTING===========

Execute SAP stuffs, I put in here what I recorded from sap record and it works OK

'=======================================

  Set session = Nothing

  connection.CloseSession ("ses[0]")

  Set connection = Nothing

  Set sap = Nothing

'End of my sub

End Sub

2 个答案:

答案 0 :(得分:1)

如果在本地客户端安装中使用SAP BAPI函数,则可以无需执行shell命令等。

VBA中的一种方法是在用于SAP功能的模块中创建对象类型的全局变量。

  1. 在同一模块的一个子例程中,创建对象并登录到SAP。
  2. 在其他子功能中执行一些操作。
  3. 使用最终子例程注销并处置该对象。

全局变量使您的会话在处理期间保持打开状态。

例如,在模块顶部的全局变量中,您可以输入:

Dim objR3 As Object  'SAP functions / connection

假设您创建一个Access表单,其中包含一些用于登录属性的文本字段(您也可以使用Excel并仅引用单元格)。然后,在登录子例程中,使用类似以下内容的

strUser = frm!txtSAPUser
strPwd = frm!txtPassword
strClient = frm!txtClient
strSystem = frm!txtSystem
strServer = frm!txtServer
Set objR3 = CreateObject("SAP.Functions")
With objR3.Connection
    .System = strSystem
    .client = strClient
    .User = strUser
    .Password = strPwd
    .language = "EN"
    .ApplicationServer = strServer
    .SystemNumber = strSystem
    '--if no logon then exit
If .logon(0, True) <> True Then
    MsgBox "Login failed.", vbExclamation, "Login"
End If
End With

然后在其他子例程中执行某些操作后,可以在注销子例程中使用注销命令:

    objR3.Connection.LOGOFF

当您对SAP接口执行一些脚本编写时,此方法将使您的连接保持打开状态。

答案 1 :(得分:1)

您可以使用函数来测试连接是否已经打开,例如...

Sub sap()

If SAP_Connection Then
MsgBox ("Sap is Open so just attached to session(0)")
Else
MsgBox ("Sap is NOT open so open Logon Window")
End If

End Sub

函数看起来像这样...

Function SAP_Connection() As Boolean

On Error GoTo ErrSap

If Not IsObject(SapApplication) Then
   Set SapGuiAuto = GetObject("SAPGUI")
   Set SapApplication = SapGuiAuto.GetScriptingEngine
End If
If Not IsObject(Connection) Then
   Set Connection = SapApplication.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 SapApplication, "on"
End If

SAP_Connection = True
Exit Function

ErrSap:
SAP_Connection = False

End Function