excel - VBA Sap Scripting 打开或连接/保留在已打开的 session 窗口中

标签 excel vba scripting sap-gui

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

如何让我的代码使用已经存在且打开的连接,或者如果它未打开,则打开它?

如果 LA-6-Prod 未打开,它可以完美运行,但无法告诉最终用户在执行宏之前确保没有打开连接窗口。

非常感谢

这是我的代码:

Sub my_sap
  Dim SapGui, Applic, connection, session, WSHShell

  strconnection = Worksheets("sap_info").Range("A2").Value
  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 Sub

最佳答案

您可以使用一个函数来测试连接是否已经打开,使用类似这样的东西......

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

关于excel - VBA Sap Scripting 打开或连接/保留在已打开的 session 窗口中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55733193/

相关文章:

vba - 将 Access 中的数据写入 Excel 文件

vba - 建议通过从左到右的列而不是使用 if 语句更有效地删除重复项

ios - 在 iOS 开发的上下文中,什么是配置/makefile 脚本的好书或引用?

bash shell : grepping between specific string and delimiter?

linux - 期望不按预期工作

excel - 基于 VBA 模板创建新的 Excel 文件

arrays - 如何通过 VBA 函数填充 Excel 工作表中的单元格?

vba - 如何使用非统一分隔符分解文本?

javascript - 如何使用 vba 宏触发特定网页事件

excel - 如何使用 excel 宏将条件格式应用于多列