How do I open a file for use globally in VBScript?

I am using the following to open a file for reading in a vbscript.  The script fails when I don't open the file in both the main section and the functions using it.  Is there a way to open the file once and make it available throughout?

Const ForReading = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(myFile.txt", ForReading)
Who is Participating?
Just do these commands outside of any functions or sunroutines. Also I like to prepend a 'g' or 's' to all global variables.

For example:

Const ForReading = 1
Set sobjFSO = CreateObject("Scripting.FileSystemObject")
Set sobjFile = sobjFSO.OpenTextFile(myFile.txt", ForReading)

Function Func1
' You can reference gobjFile here
End Function

Sub Sub1
' You can reference gobjFile here
End Function
Opps...that last line should be 'End Sub'. But hopefuly you get the concept. Any variables / statements outside a function or subroutines are global or script variables and can be referenced by all functions in the same file.
Bill PrewCommented:
In addition to the above approach, I'll mention that it's actually enough just to DIM the variable you want to share outside of any functions, in the "main" body of the script.  Once the variable has been DIM'ed in that way, it can be referenced in any location in the code, and you could even have a subroutine or function that did the actual open of the file as long as the object you assign that too was DIM'ed outside of the routine.  Here's a simple example to demonstrate this:

Option Explicit
Dim PublicVar1
Wscript.Echo PublicVar1

Sub DoSub()
   PublicVar1 = "hello"
End Sub

Open in new window

jrslimAuthor Commented:
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.