VBScript Includes – How to Add an Existing Script with a Simple Include Statement

In ASP there is a really easy way to include existing files in your scripts. There is a simple “include file” or “include virtual” statement you can use to add functionality that is in other files that you have written. Well there was really no equivalent functionality in VBScript until VBScript 5.0 was released. When VBScript 5.0 came out there were options to execute strings as if they were native VBScript code.

A guy named Eric Lippert talks about the reasoning behind why he added the different functionality he added and explains very lucidly how to utilize the different functionality. Well in order to make it more useful for myself I decided, as usual, to write a little sub that I could simply add to the bottom of my script.

This particular sub is simply called “Include”. You can add existing scripts by simply calling the file you’d like to include in the following manner: “Include “filename.vbs””. After invoking the sub the code you “include” will be executed immediately. If the file you’re including is a sub or a function, you can call it just like you would any other function that you’d add normally to your scripts.

Here’s the code:

Sub Include(sIncludeFile)
  'This script is provided under the Creative Commons license located
  'at http://creativecommons.org/licenses/by-nc/2.5/ . It may not
  'be used for commercial purposes with out the expressed written consent
  'of NateRice.com

  Const OpenAsDefault = -2
  Const FailIfNotExist = 0
  Const ForReading = 1

  Set oIncludeFSO = CreateObject("Scripting.FileSystemObject")

  'Check for existance of include
  If Not oIncludeFSO.FileExists(sIncludeFile) Then
    Wscript.Echo "Error: Include File Not Found."
    Exit Sub
  End If

  Set oIncludeFile = oIncludeFSO.OpenTextFile(sIncludeFile, ForReading, _
  FailIfNotExist, OpenAsDefault)

  sIncludeCode = oIncludeFile.ReadAll
  Set oIncludeFSO = Nothing
  Set oIncludeFile = Nothing

  'Execute Include
  ExecuteGlobal sIncludeCode 

End Sub


Leave a Comment