Adventures in VBScript – Including code from other files
If you’re a VBScript hack like me, you’re probably frustrated by the inability of VBScript to include code from other files natively. Yes, you can use funky Job files etc, but nothing beats the simplicity of an all-in-one .VBS.
I’ve created innumerable “helper” scripts and classes over the years, and even wrote a tool I call “region” which selectively merges different files together to make one big (unreadable) script.
My utopia of having simple, small scripts which leveraged my 20 year programming library has not been achieved, until now.
Here you’ll find my “Include for VBS” function – surprisingly simple, but it took 20 years of thinking about it before I got around to writing it. There were two problems to solve:
1. How to read code from another file and have it available to the script
That’s the easy part – VBScript easily reads text files, and the executeglobal statement allows you to “add” code to the runtime in memory.
2. Don’t include things twice, or three times etc
Harder – as it requires the include function to track what modules it’s loaded. Since the Include function might be in a class, we need to make sure we don’t include things multiple times for multiple classes etc – it’s all to do with scope.
Thankfully the executeglobal and eval functions come to our aid again – we can use them to create variables on the fly in the global workspace which we can use to track which files we’ve loaded.
So, with those problems solved – here’s my snippit to reliably include files ONCE in your VBScripts, saving you duplicating the same code over and over again.
Sub Include(fSpec) ' Sub to load file modules (Once!) ' Simply call this function with the path to the vbs file you want to include, and it will be ' loaded into memory ONCE, even if you try to load it a number of times. Dim sTemp On Error Resume Next sTemp = Eval("ICLF") On Error Goto 0 If IsEmpty(sTemp) Then ' no currently loaded files - first Include run ExecuteGlobal "Dim ICLF : ICLF = 0" End If ' test to see if file has already been loaded If InStr(1,iclf,fspec,vbTextCompare)=0 Then With CreateObject("Scripting.FileSystemObject") If .fileexists(fspec) Then ExecuteGlobal .openTextFile(fSpec).readAll() Else MsgBox "Include file " & fspec & " not found. Exiting",vbOKOnly+vbExclamation,"Critical Error." WScript.Quit End If End With ICLF = ICLF & "|" & fspec Else ' file already loaded End If End Sub