对与 SAP 的连接 Excel VBA 进行故障排除

Troubleshooting connection Excel VBA to SAP

我正在尝试通过 Excel VBA 连接到 SAP GUI,以便自动从 SAP 提取许多数据。我在连接过程的不同位置看到了与连接错误相关的类似问题,但是我没有在连接代码的“GetObject'SAPGUI'”部分遇到任何直接解决代码的问题。

这是我迄今为止尝试过的代码,代码注释中写有相应的错误:

Sub SAP()

If Not IsObject(application) Then
   Set SapGuiAuto = GetObject("SAPGUI") 
   Set application = SapGuiAuto.GetScriptingEngine 'This outputs "compile error: Invalid use of property"
End if
...
End Sub

我认为 application 是 VBA 中的保留关键字,它通过引用不正确的对象而导致错误。然后我重命名为一个唯一的变量名'Sapplication',在不同的位置触发错误:

Sub SAP()

If Not IsObject(sapplication) Then
   Set SapGuiAuto = GetObject("SAPGUI") 'This now outputs "Automation Error, Invalid syntax -2147221020"
   Set sapplication = SapGuiAuto.GetScriptingEngine 
End if
...
End Sub

根据 SAP 论坛的建议,建议我将 GetObject("SAPGUI") 替换为 CreateObject("SAPGUI.Application"),这会提示一个新错误:

Sub SAP()

If Not IsObject(sapplication) Then
   Set SapGuiAuto = CreateObject("SAPGUI.Application") 
   Set sapplication = SapGuiAuto.GetScriptingEngine 'Object doesn't support this method or property (438)
End if
...
End Sub

不确定这段代码哪里出错了,原始代码似乎很标准,关于其他人从 SAP 中记录的宏中获得的内容。关于我在这里可能出错的地方有什么想法或建议吗?

UPDATE/EDIT: 在全新的 SAP window 和 Excel 启动后,我能够成功地进一步编写代码。但是,我遇到了一个新问题,似乎没有创建连接对象(或者至少没有与我可以引用的连接对象相关的实例):


Set rotEntry =GetObject("SAPGUI")
Set sapplication = rotEntry.GetScriptingEngine 'I did confirm that use of 'application is conflicting per the SAP GUI documentation, so replaced with sapplication.
Set Connection = sApplication.children(0) 'Error: The enumerator of the collection cannot find an element with specified index


我发现有时我需要尝试使用稍微不同的登录脚本,例如:

If Not IsObject(SapApp) Then
    On Error Resume Next
    Set SapGuiAuto = CreateObject("SAPGUI")
    If SapGuiAuto Is Nothing Then
        Err.Clear
        Set SapGuiAuto = GetObject("SAPGUISERVER")
    End If
    On Error GoTo 0
    
    Set SapApp = SapGuiAuto.GetScriptingEngine    'Object doesn't support this method or property (438)
End If

经过大量的反复试验,我发现通过 shell 命令打开而不是当前打开 GUI 是成功的。我在下面发布了目前为我工作的代码:

Sub sap()


Dim sapgui
Dim applic
Dim connection
Dim session
Dim wshshell

Shell "C:\Program Files (x86)\SAP\FrontEnd\SapGui\saplogon.exe", vbNormalFocus 'OPEN SAP LOGON PAD 'edit to desired path
Set wshshell = CreateObject("WScript.shell")
Do Until wshshell.AppActivate("SAP Logon")
Application.Wait Now + TimeValue("0:00:02") 'set a delay timer to ensure the shell logon is ready

Loop

Set wshshell = Nothing
Set sapgui = GetObject("SAPGUI")
Set applic = sapgui.Getscriptingengine
Set connection = applic.OpenConnection("PA4 - Production North America ERP", True) 'edit this to reach the desired section within SAP

Set session = connection.Children(0)

'INSERT AUTOMATED MARCO HERE

End sub