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

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

Leave a Comment