【问题标题】:VBscript runtime errorVBscript 运行时错误
【发布时间】:2010-12-28 20:27:05
【问题描述】:

我有一个正在构建的 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 

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

【问题讨论】:

    标签: vbscript


    【解决方案1】:

    objFSO 从未被赋值。出错时objFSO的值为Empty,不是对象。

    你可能错过了

       Set objFSO = CreateObject("Scripting.FileSystemObject")
    

    【讨论】:

    • 感谢您的回复 - 我现在将测试它并让您知道结果!
    【解决方案2】:

    @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 .

    【讨论】:

      【解决方案3】:

      如果你使用的有点像:

      Set objFSO = CreateObject("Scripting.FileSystemObject") 
      
      strVar = ReadFileIntoArray(File)
      

      它进入Function,然后你不需要重新分配一个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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多