baboufight
baboufight

Reputation: 133

Create and manage Log.txt file

I have vba code to run which include many functions, and I would like to add a function called "WriteLog" which will create (if it not already exist) a text file named Log.txt and write the string "text" (passed as argument) to this file.

I want this function to be launch from several other functions to monitor their execution. My problem is that my actual code overwrite the text file, instead of adding a new line into it when I call my function.

Here my actual code :

Function WriteLog(text)
    Dim fso As Object
    Set fso = CreateObject("Scripting.FileSystemObject")
    Dim oFile As Object
    Set oFile = fso.CreateTextFile("C:\Log.txt", True)
    oFile.writeline (text)
    oFile.Close
    Set fso = Nothing
    Set oFile = Nothing
End Function

Sub Logtesting()
    WriteLog ("Testing")
    WriteLog ("123")
End Sub

Output result:

123

Upvotes: 1

Views: 466

Answers (2)

o.carltonne
o.carltonne

Reputation: 385

use OpenTextFile instead of CreateTextFile.

fso.OpenTextFile(filename, 8)

MSDN - OpenTextFile Documentation

Function WriteLog(text)
    Dim fso As Object
    Set fso = CreateObject("Scripting.FileSystemObject")
    Dim oFile As Object
    Set oFile = fso.OpenTextFile("C:\Log.txt", 8)
    oFile.writeline text
    oFile.Close
    Set fso = Nothing
    Set oFile = Nothing
End Function

Upvotes: 1

Leo Chapiro
Leo Chapiro

Reputation: 13984

You need to use OpenTextFile instead of CreateTextFile like this:

' Set oFile = fso.CreateTextFile("C:\Log.txt", True)

Set oFile = fso.OpenTextFile("C:\Log.txt", ForAppending, True)

Upvotes: 1

Related Questions