常見的高階程式語言都可以引用外部檔案來執行,如:
HTML:< !-- #include file="file path"-- >
C/C++:#include "file path" or #include
C#:using < module name >
Python:import
JAVA:#include < file path >
PHP:include 'file path'
以下使用兩個VBS檔,來說明如何使用在VBScript引用其他外部VBS檔案,讀者可參考以下程式碼內容。
在Test.vbs檔案中輸入以下程式碼。
sub WriteLog(msg) wscript.echo now & ": " & msg end sub sub MsgLog(msg) wscript.echo now & ": " & msg end sub
在Main.vbs中輸入輸入以下程式碼。
Include("Test.vbs") WriteLog "Start of Script!" Sub Include (strFile) 'Create objects for opening text file Set objFSO = CreateObject("Scripting.FileSystemObject") if objFSO.fileexists(strFile) then Set objTextFile = objFSO.OpenTextFile(strFile, 1) 'Execute content of file. ExecuteGlobal objTextFile.ReadAll Else MsgBox "Include file " & strFile & " not found. Exiting", vbOKOnly + vbExclamation, "Critical Error." WScript.Quit End If 'CLose file objTextFile.Close 'Clean up Set objFSO = Nothing Set objTextFile = Nothing End Sub
點擊Main.vbs可以見到Main.vbs在執行時,會去呼叫Test.vbs中的WriteLog函數來執行。
也可以將Main.vbs的程式換成以下內容,結果也是一樣。
execute "incFile = ""test.vbs"":Set objFS = CreateObject(""Scripting.FileSystemObject""):set objIFile = objFS.GetFile(incFile):set objITS = objIFile.OpenAsTextStream(1, 0):Execute objITS.Read(objIFile.Size):objITS.Close:set objITS = nothing:set objIFile = nothing:set objFS = nothing" WriteLog "Start of Script!"
參考資料:
- Using "include files" VBScript Programs
- Include other files in VBScript
- Adventures in VBScript – Including code from other files