This is a function that will add a class from an external file. It is as close to a #include that I have been able to come up with in VBScript. The class that you want to add needs to be saved in a file and must be valid vbscript. Here is an example of its use (the example assumes that there is a valid class file in the same directory as the test code is running in and that the valid class file is named LoggerClass.vbs):
Option Explicit
Dim arrReturn
'This is an example of trying to load a class from a file that does not exist. This will fail.
arrReturn = AddClass("Fail.vbs")
WScript.Echo "Fail: " & arrReturn(0) & " - " & arrReturn(1)
'This line will load a class from the file LoggerClass.vbs as long as that file is present
arrReturn = AddClass("LoggerClass.vbs")
WScript.Echo "Success: " & arrReturn(0) & " - " & arrReturn(1)
This test code should produce this output:
Fail: 1 - The specified class file Fail.vbs does not exist
Success: 0 -
Here is the actual function:
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
''
'' Function AddClass(strClassFile)
'' Author: ebgreen
'' Purpose: Imports a class that is stored in an external file.
'' Takes: strClassFile - The name of the file with the class To
'' import. Must be a valid path.
'' Returns: Array - (0)= The return code. 0 means success otherwise
'' it will be the error code returned by
'' the operation that failed.
'' (1)= Any error message. Will be "" if success
'' Revision History:
'' 12/23/05 RMD Revision History Added
''
'' To Do:
'' Nothing at present
''
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function AddClass(strClassFile)
Dim oFSO, oFile, strFile
Set oFSO = CreateObject ("Scripting.FileSystemObject")
'Check to see if the file to be loaded exists. If it does not, return an error
If Not oFSO.FileExists(strClassFile) Then
AddClass = Array("1", "The specified class file " _
& strClassFile & " does not exist")
Exit Function
End If
On Error Resume Next
Err.Clear
'OPen the file to be loaded. If the open fails, return an error.
Set oFile = oFSO.OpenTextFile(strClassFile)
If Err.Number <> 0 Then
AddClass = Array(Err.Number, _
"The specified class file " & strClassFile _
& " could not be opened for reading.")
Exit Function
End If
On Error GoTo 0
'The file object is created so read all of the file and ececute it globally to load the class for use
strFile = oFile.ReadAll
oFile.close
Set oFso = Nothing
Set oFile = Nothing
ExecuteGlobal strFile
AddClass = Array("0", "")
End Function EDIT: Added comments
<message edited by ebgreen on Wednesday, January 04, 2006 4:27 AM>