VBscript运行时错误

时间:2010-12-28 20:27:05

标签: vbscript

我正在制作一个VBScript。脚本本身完成了其中的所有功能 - 它只在脚本结束后才会抛出错误。它给了我以下错误:     vbscript运行时错误:对象需要'objFSO'

这是相关函数:

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 

文件仍然打开并正常使用。我有点失落。有什么想法吗?

3 个答案:

答案 0 :(得分:3)

永远不会为

objFSO分配值。发生错误时,objFSO的值为Empty,这不是对象。

你可能错过了

   Set objFSO = CreateObject("Scripting.FileSystemObject")

答案 1 :(得分:0)

@Nutsy:@Thom Smith有答案,我认为您可能需要明确设置您希望如何打开文件。我已将您的代码更新为包含一些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

脚本中可能还有其他一些问题,我不确定redim preserve text(nlines)将会做什么,因为您再也没有在任何地方定义或使用text而且您从未定义或初始化nlines } 0

答案 2 :(得分:0)

如果您使用的有点像:

Set objFSO = CreateObject("Scripting.FileSystemObject") 

strVar = ReadFileIntoArray(File)

它进入函数,然后你不需要重新分配一个objFSO只写:

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