Skip to main content

SAP GUI Scripting API

脚本录制与回放

'录制的vb代码
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 application, "on"
End If
session.findById("wnd[0]").maximize
session.findById("wnd[0]/usr/txtRSYST-BNAME").text = "user001"
session.findById("wnd[0]/usr/pwdRSYST-BCODE").text = "********"
session.findById("wnd[0]/usr/pwdRSYST-BCODE").setFocus
session.findById("wnd[0]/usr/pwdRSYST-BCODE").caretPosition = 7
session.findById("wnd[0]").sendVKey 0

如果直接把上述录制的vb代码拷贝至excel宏,将无法编译通过。原因是VBA中的Application是保留字,它指的是整个Excel应用实例。要消除这个编译错误,其实方法超简单,用别的对象名来指代它便是,修改后的VBA代码如下:

Sub sapAutomation()
'通过VBA连接SAP GUI实现自动化登录
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 Application, "on"
End If
session.findById("wnd[0]").maximize
session.findById("wnd[0]/usr/txtRSYST-BNAME").Text = "user001"
session.findById("wnd[0]/usr/pwdRSYST-BCODE").Text = "********"
session.findById("wnd[0]/usr/pwdRSYST-BCODE").SetFocus
session.findById("wnd[0]/usr/pwdRSYST-BCODE").caretPosition = 7
session.findById("wnd[0]").sendVKey 0

End Sub

参考

https://www.cnblogs.com/new-june/p/16372559.html