繁体   English   中英

故障排除 Excel VBA 到 SAP 的连接

[英]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 中记录的宏中获得了什么。 关于我可能在哪里出错的任何想法或建议?

更新/编辑:在新的 SAP window 和 Excel 启动后,我能够成功地在代码中取得进一步进展。 但是,我遇到了一个新问题,似乎没有创建连接 object (或至少与我可以参考的该连接 object 相关的实例):


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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM