建立包含檔案方法

所以這個功能的主要目標是:

  • 是獨立的,因為它需要在主 VbScript 檔案中編寫,並且不能在包含的檔案中(因為它定義了 include 函式)
  • 如果出現問題(例如,包含的檔案,發生的錯誤,……),請提供足夠的資訊
  • 包含一次檔案,只包含一次以避免包含迴圈。
' *************************************************************************************************
'! Includes a VbScript file
'! @param p_Path    The path of the file to include
' *************************************************************************************************
Sub IncludeFile(p_Path)
    ' only loads the file once
    If std_internal_LibFiles.Exists(p_Path) Then
        Exit Sub
    End If
    
    ' registers the file as loaded to avoid to load it multiple times
    std_internal_LibFiles.Add p_Path, p_Path

    Dim objFso, objFile, strFileContent, strErrorMessage
    Set objFso = CreateObject("Scripting.FileSystemObject")
    
    ' opens the file for reading
    On Error Resume Next
    Set objFile = objFso.OpenTextFile(p_Path)
    If Err.Number <> 0 Then
        ' saves the error before reseting it
        strErrorMessage = Err.Description & " (" &  Err.Source & " " & Err.Number & ")"
        On Error Goto 0
        Err.Raise -1, "ERR_OpenFile", "Cannot read '" & p_Path & "' : " & strErrorMessage
    End If
    
    ' reads all the content of the file
    strFileContent = objFile.ReadAll
    If Err.Number <> 0 Then
        ' saves the error before reseting it
        strErrorMessage = Err.Description & " (" &  Err.Source & " " & Err.Number & ")"
        On Error Goto 0
        Err.Raise -1, "ERR_ReadFile", "Cannot read '" & p_Path & "' : " & strErrorMessage
    End If
    
    ' this allows to run vbscript contained in a string
    ExecuteGlobal strFileContent
    If Err.Number <> 0 Then
        ' saves the error before reseting it
        strErrorMessage = Err.Description & " (" &  Err.Source & " " & Err.Number & ")"
        On Error Goto 0
        Err.Raise -1, "ERR_Include", "An error occurred while including '" & p_Path & "' : " & vbCrlf & strErrorMessage
    End If
End Sub