Friday, 7 February 2014

VBScript - call a function in another file (Updated)

In a recent post about how to make an email signature using VBScript, I re-used a piece of code that allows you to call a function in another file with VBScript. This was subject of a post back in August, but back then I felt the post and the code was a bit convoluted Therefore, here's the tidier and more easy readable version.


As before there are two files and you can grab them from my website here:

These two files in the .zip are:
  • callerModule.vbs
  • mySubLib.vbs
Here's what they look like.


Option Explicit

' This is the Sub that opens external files and reads in the contents.
' In this way, you can have separate files for data and libraries of functions
Sub Include(yourFile)
  Dim oFSO, oFileBeingReadIn   ' define Objects
  Dim sFileContents            ' define Strings
  Set oFSO = CreateObject("Scripting.FileSystemObject")
  Set oFileBeingReadIn = oFSO.OpenTextFile(yourFile & ".vbs", 1)
  sFileContents = oFileBeingReadIn.ReadAll
  ExecuteGlobal sFileContents
End Sub

' Here we call the Include Sub, then pass it the name of the file we want items from
Include "mySubLib"

' Now we can call items from the files we read in, whenever we want to use them


In the above, we create a new File System Object that allows us to read in the contents of another file. Doing that first loads it into memory and we use the contents of the file as if it were all in one big file.

What this means is we have a simple way to call a method from another VBScript or to call a class, Sub, some text or whatever you want from another VBScript. Useful to make our VBScript a bit more like other scripting languages. When I've seen QTP and UFT automation it's essentially the approach used.


Sub MySub
  MsgBox "If you can see this message, you just called a method in another file.", vbOKCancel, "Called from a file outside the one you ran"
End Sub 'MySub

This is the Sub being called, but it could be a Method, etc. as stated above.

That's it, the tidier version, have fun!


By the way, if you can't get the .zip file, just copy and paste the above into two .vbs files as named above. Say thanks by a Subscribe to my YouTube Channel or following the Blog!