我正在通过VBA连接到SAP GUI,但无法弄清楚如何在其自身功能内建立连接。这是假设您已经登录到SAP GUI。我收到“对象变量或未设置块变量”错误。
这是一个有效的例子...
Sub runProgram()
'Connet to SAP."sapguiapp", used to be named "Application" which is an excel keyword
If Not IsObject(sapguiapp) Then
Set SapGuiAuto = GetObject("SAPGUI")
Set sapguiapp = SapGuiAuto.GetScriptingEngine
End If
If Not IsObject(Connection) Then
Set Connection = sapguiapp.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 sapguiapp, "on"
End If
'Maximize the SAP window
session.findById("wnd[0]").maximize
' Do a whole bunch of other SAP work, now that we're connected
'....
End Sub
但是,我想将连接部分拆分为自己的子功能,以使其与实际工作分开。我以为我可以简单地创建一个新函数并将“会话”作为对象返回。
这不起作用:
Sub runProgram()
'Call the function that connects to SAP
Dim session As Object
Set session = ConnectToSAP
'Maximize the SAP window
session.findById("wnd[0]").maximize
' Do a whole bunch of other SAP work, now that we're connected (JK, we're not...)
'....
End Sub
Function ConnectToSAP() As Object
'Connet to SAP."sapguiapp", used to be named "Application" which is an excel keyword
If Not IsObject(sapguiapp) Then
Set SapGuiAuto = GetObject("SAPGUI")
Set sapguiapp = SapGuiAuto.GetScriptingEngine
End If
If Not IsObject(Connection) Then
Set Connection = sapguiapp.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 sapguiapp, "on"
End If
End Function
我很想念我是否有些痛苦吗?我有一些连接到SAP的潜艇,所以我想拆分出实际的连接代码。任何提示将不胜感激!
编辑:请注意,我没有从我的实际程序中复制/粘贴此内容,因此,如果有一个小的错字,我深表歉意。请发表评论,让我知道我在哪里搞砸了:)
答案 0 :(得分:1)
在<
函数中,您最后缺少赋值语句ConnectToSAP
。
答案 1 :(得分:0)
我建议使用Option Explicit
并正确声明变量。
如果您添加对sapfewse.ocx
的引用(位于SAP安装文件夹C:\Program Files (x86)\SAP\FrontEnd\SAPgui\sapfewse.ocx
中),甚至可以使用VBA intellisense。
如果您不想添加引用,请使用Object
代替SAPFEWSLib.GuiSession
,SAPFEWSLib.GuiConnection
和SAPFEWSLib.GuiApplication
。
Option Explicit
Function ConnectToSAP() As SAPFEWSELib.GuiSession
Dim SapGuiAuto As Object
Dim SapGuiApp As SAPFEWSELib.GuiApplication
Dim connection As SAPFEWSELib.GuiConnection
On Error GoTo Err1
Set SapGuiAuto = GetObject("SAPGUI")
Set SapGuiApp = SapGuiAuto.GetScriptingEngine
On Error GoTo Err2
Set connection = SapGuiApp.Connections(0)
Set ConnectToSAP = Connection.Sessions(0)
Exit Function
Err1:
MsgBox "Please launch SAP"
Exit Function
Err2:
MsgBox "Please login to SAP"
End Function
WScript
是vbscript对象,在vba中不存在。
它的ConnectObject
方法用于事件处理,尽管您确实需要一个类模块并声明会话变量WScript
,但它可以在VBA中完成,而无需使用WithEvents
对象:< br />
类模块:
Private WithEvents session As SAPFEWSELib.GuiSession
Private requestCounter As Long
Private Sub session_startRequest(session As SAPFEWSELib.GuiSession)
requestCounter = requestCounter + 1
End Sub