r/visualbasic • • Jun 15 '18

Trying to clean up my code by creating the objects of SAP in it's own sub?

I have dozens of small functions, and before each I have to do something like the code below. Is it possible to write this only once somewhere in my code and call it every time I need it?

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
6 Upvotes

5 comments sorted by

1

u/Bonejob VB Guru Jun 15 '18

Globalize the check and do once per startup by exposing the 3 objects checked.

OR

Do what /u/ViperSRT3g suggested and abstract this to a function called something like "checkObjects"

1

u/djdadi Jun 15 '18

Globalize the check and do once per startup by exposing the 3 objects checked.

That sounds like what I need to do. How do I go about that? I tried searching for "exposing vba objects" but didn't see anything directly relevant.

I'm pretty new to VBA

1

u/Bonejob VB Guru Jun 15 '18
Global SapGuiAuto as GetObject("SAPGUI")
Global SAPapplication as SapGuiAuto.GetScriptingEngine

I believe that's it. been a while since working in COM VB syntax.

1

u/djdadi Jun 15 '18

Does not work, errors on both lines (the second because the first doesn't work). Do you know any good tutorial or documentation on this topic?

1

u/ViperSRT3g Application Specialist Jun 15 '18

You could put it in its own sub and call that from each function.