Nutsy
Nutsy

Reputation: 1

VBscript runtime error

I have a VBScript that I am working on building. The script itself complets all of the functions within it - it throws an error only after the script ends. It is giving me the following error: vbscript runtime error: Object required 'objFSO'

Here is the relavant function:

Function ReadFileIntoArray (sFile)
    dim objFSO 'As FileSystemObject
    dim file
    dim volumes()

    Set file = objFSO.OpenTextFile(sFile)  'Error Thrown Here.
    do while not file.AtendOfStream
        redim preserve text(nlines)
        volumes(nlines) = file.Readline
        nlines = nlines + 1
    loop

    file.close
    set file = nothing
    Set objFSO = nothing

    ReadFileIntoArray = volumes
end Function 

The file is still opened and used properly. I'm a little lost. Any ideas?

Upvotes: 0

Views: 7196

Answers (3)

s_mj
s_mj

Reputation: 580

If you are using somewhat like:

Set objFSO = CreateObject("Scripting.FileSystemObject") 

strVar = ReadFileIntoArray(File)

it goes into the Function, then you need not to reassign an objFSO just write:

Function ReadFileIntoArray (sFile)

dim file
dim volumes()

Set file = objFSO.OpenTextFile(sFile)  'Error Thrown Here.
do while not file.AtendOfStream
    redim preserve text(nlines)
    volumes(nlines) = file.Readline
    nlines = nlines + 1
loop

file.close
set file = nothing
Set objFSO = nothing

ReadFileIntoArray = volumes
end Function

Upvotes: 0

stealthyninja
stealthyninja

Reputation: 10371

@Nutsy: @Thom Smith has the answer, I just think you might need to explicitly set how you wish to open the file as well though. I've updated your code to include some constants:

Function ReadFileIntoArray (sFile)
    dim objFSO 'As FileSystemObject
    dim file
    dim volumes()

    Const ForAppending = 8
    Const ForReading   = 1
    Const ForWriting   = 2

    Set objFSO = CreateObject("Scripting.FileSystemObject")        
    Set file = objFSO.OpenTextFile(sFile, ForReading)  'Error Thrown Here.
    do while not file.AtendOfStream
        redim preserve text(nlines)
        volumes(nlines) = file.Readline
        nlines = nlines + 1
    loop

    file.close
    set file = nothing
    Set objFSO = nothing

    ReadFileIntoArray = volumes
end Function

There may be some other issues in the script as well, I'm unsure what redim preserve text(nlines) will do since you never define or use text anywhere again and you never define or initialise nlines as 0 either.

Upvotes: 0

Thom Smith
Thom Smith

Reputation: 14086

objFSO is never assigned a value. When the error occurs, objFSO's value is Empty, which is not an object.

You're probably missing

   Set objFSO = CreateObject("Scripting.FileSystemObject")

Upvotes: 3

Related Questions