如何读取文件并将 return 内容作为函数的结果?

How can I read a file and return the content as the result of a function?

我在 Visual Basic 上有两个函数用于读写一个文件

问题出在读取函数中。 return 句子没有 return 任何东西。我只想读文件的第一行

我做错了什么?为什么 return 不把值放在文本变量中?

Function readfile()

    Dim objFSO
    Dim objLF
    Dim text

    Set objFSO = CreateObject("Scripting.FileSystemObject")     

    on error resume next 
    Set objLF= objFSO.OpenTextFile ("file.txt",1,false)

    if Err.Number <> 0 Then

        Wscript.echo "error"

    else

        text = objLF.ReadLine  
        objLF.Close
        return text

    end if



    On Error Goto 0 

End Function

return text 不是 Visual Basic,而是 C(以及派生语言,如 JScript)。所以应该是ReadFile=Text,函数名等于所有Basics中的return值

你使用on error是合适的,但是打开文件操作后你应该使用On Error Goto 0关闭它。

To return a value from a function, assign the value to the function name. Any number of such assignments can appear anywhere within the procedure. If no value is assigned to name, the procedure returns a default value: a numeric function returns 0 and a string function returns a zero-length string (""). A function that returns an object reference returns Nothing if no object reference is assigned to name (using Set) within the Function.

https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/function-statement

帮助文件位于 http://download.microsoft.com/download/winscript56/Install/5.6/W982KMeXP/EN-US/scrdoc56en.exe