Importing VBS Files In Your VBScript Project

If you have certain functions you use over and over , why not compile them all into a single library file , and simply “Import” them into your new projects, like a real object oriented language does?.

If your one of those people that has a script to do everything , you may find the need to organise your functions and files necessary. You can use this method to store configuration options too.

Here’s how.

Place all your commonly used functions in a new .vbs file , say something like “Library.vbs”

From your new script project , add the Import function at the bottom of the script.

At the top of the script ,” Import” your Library.vbs file .

You can now call on any functions or subs from within your new project , the same as though it was written in the current file.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
'===================================================

'                 Import Code

'===================================================

Sub Import(strFile)
 
   Set objFs = CreateObject("Scripting.FileSystemObject")
 
   strFile = WshShell.ExpandEnvironmentStrings(strFile)
 
   strFile = objFs.GetAbsolutePathName(strFile)
 
   Set objFile = objFs.OpenTextFile(strFile)
 
   strCode = objFile.ReadAll
 
   objFile.Close
 
   ExecuteGlobal strCode
 
End Sub

Usage

1
Import "Library.vbs"

2 Responses to “Importing VBS Files In Your VBScript Project”

  1. Frank  on December 27th, 2008

    That is exactly what I am looking. I was about to learn perl so that I could have the same functionality. If it works without any hiccups, you will have saved me hours and hours of work.

    Thanks!!!

  2. GroLis  on February 24th, 2010

    Hello! I have a problem with your function. I get an “File not found” error, when I run my script with this function.

    Here is my code:
    Sub Import(strFile)
    Dim WshShell : Set WshShell = WScript.CreateObject(“WScript.Shell”)
    Dim objFs : Set objFs = CreateObject(“Scripting.FileSystemObject”)

    strFile = WshShell.ExpandEnvironmentStrings(strFile)
    strFile = objFs.GetAbsolutePathName(strFile)

    Dim objFile : Set objFile = objFs.OpenTextFile(strFile)

    strCode = objFile.ReadAll
    objFile.Close
    ExecuteGlobal strCode
    End Sub

    Do you have an idea, what the error is? I import a file with Import “Common.vbs”. The file is in the same folder as the running script.
    Thanky you for your help. :)


Leave a Reply