How do I include a common file in VBScript (similar to C #include)?

paxdiablo picture paxdiablo · Nov 25, 2008 · Viewed 85k times · Source

VBScript doesn't appear to have a way to include a common file of functions.

Is there a way to achieve this?

Answer

paxdiablo picture paxdiablo · Nov 25, 2008

You can create a (relatively) small function in each file that you want to include other files into, as follows:

sub includeFile (fSpec)
    dim fileSys, file, fileData
    set fileSys = createObject ("Scripting.FileSystemObject")
    set file = fileSys.openTextFile (fSpec)
    fileData = file.readAll ()
    file.close
    executeGlobal fileData
    set file = nothing
    set fileSys = nothing
end sub

and then use it to include specific files - these are executed as if they were inline.

includeFile "commonapi.vbi"
includeFile "dbcalls.vbi"

It basically opens the file, reads the entire contents into a string, then executes that string. There's no error handling on the I/O calls since this sort of stuff is usually done once on program start, and you want to fail if there's a problem including it.


Note that the includeFile function can be compressed to:

Sub includeFile(fSpec)
    With CreateObject("Scripting.FileSystemObject")
       executeGlobal .openTextFile(fSpec).readAll()
    End With
End Sub

Or even to (if you're not adverse to long lines):

Sub includeFile(fSpec)
    executeGlobal CreateObject("Scripting.FileSystemObject").openTextFile(fSpec).readAll()
End Sub