Importing vbscript code at runtime

Many script languages have an import function that allows to import and execute code that is stored in another file. Microsoft's vbscript however is lacking such functionality. This page shows how it can be accomplished to import and execute vbscript code that is stored in another file.

Assume that you have the following file with some functions that you have defined:

' Filename = modMathFunction.vbs
Function Square(intNumber)
    Square = intNumber * intNumber
End Function

Normally you would have to copy this function in each script in which you want to use this function. It is however possible to define an import function in your vbscript code via which you can use this function without having to copy it.

' Filename = main.vbs

' Put the import statements at the top of your code for easier readability.
Import "modMathFunction.vbs"

' Call the Square function that you just imported.
WScript.Echo "The square of 2 is " & Square(2)

' Finally, define the Import function. I usually put it at the bottom of my main file.
Sub Import(strFile)
    Dim objFile, strCode, objFSO
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objFile = objFSO.OpenTextFile(strFile)
    strCode = objFile.ReadAll
    objFile.Close
    ExecuteGlobal strCode
    Set objFile = Nothing
    Set objFSO = Nothing
End Sub

In this way, you can store the functions that you use in multiple scripts in a few central library files. 

The advantage of this approach is that all your scripts will immediately use the latest version of your functions. 
The downside is that it makes debugging a bit harder. Since vbscript evaluates the code at runtime, it cannot tell you on which line an error occurred.

Tags: 

You might also be interested in...