0

I have two functions on Visual Basic for read and write one file

The problem is in the read Function. The return sentence doesn't return anything. I only want read the first line of the file

What Am i doing wrong? Why does the return not put the value in the text variable?

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
Geert Bellekens
  • 12,788
  • 2
  • 23
  • 50
Nephilina
  • 3
  • 1

1 Answers1

1

return text is not Visual Basic but C (and derived languages like JScript). So it should be ReadFile=Text, The name of the function is equal to the return value in all Basics.

Your use of on error is appropriate, but you should use On Error Goto 0 to turn it off after the open file operation.

To

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://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/function-statement

Help file is at http://download.microsoft.com/download/winscript56/Install/5.6/W982KMeXP/EN-US/scrdoc56en.exe

  • Then, Is it the solution? @user14122392 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 readfile= text end if On Error Goto 0 End Function – Nephilina Nov 23 '20 at 07:16
  • What happened when you tried it. I'm not sure why you are asking me what happened when you tried it. – user14122392 Nov 23 '20 at 07:18
  • already works, thank you. I already have work one part of the program. Now i need help with the Write function. I want overwrite only the first line. on error resume next Set objFSO = CreateObject("Scripting.FileSystemObject") Set objWF = objFSO.OpenTextFile ("file.txt",2,false) if Err.Number <> 0 Then Wscript.echo "error" else textfile = objWriteFile.Write(readfile()) objWF.close Wscript.echo textfile end if On Error Goto 0 Note: All need variable are declarated – Nephilina Nov 23 '20 at 07:49
  • 1
    @Nephilina Please don't post code in comments. That is not readable at all. If you have a new question you should post it as a question. – Geert Bellekens Nov 23 '20 at 10:13