Reputation: 590
I'm creating a logging module for my application.
I'm receiving the following error on the Sub WriteToLog
when trying to write to the text file:
"Error 54 - Bad File Mode"
Line: "fileStream.WriteLine Prefix & Data"
I based that sub off of the answer here
Any idea what I'm doing wrong? Here's my code so far:
Private CurrentLogName As String
Public Enum LogLevel
Info = 0
Error = 1
End Enum
Public Sub WriteToLog(ByRef Data As String, ByRef LogLevel As Integer)
Dim fso As FileSystemObject
Set fso = New FileSystemObject
Dim fileStream As TextStream
On Error GoTo FileError
Set fileStream = fso.OpenTextFile(CurrentLogName)
Dim Prefix As String
Select Case LogLevel
Case 0
Prefix = "[Info] "
Case 1
Prefix = "[Error] "
'TODO more cases
End Select
fileStream.WriteLine Prefix & Data
fileStream.Close
fso = Nothing
fileStream = Nothing
GoTo EndSub
FileError:
MsgBox "An error occurred while writing to the log file." & vbCrLf & Err.Description,
vbCritical, "Error"
GoTo EndSub
EndSub:
End Sub
Private Sub test()
CreateLogFile
Call WriteToLog("Test", LogLevel.Error)
End Sub
Upvotes: 2
Views: 1349
Reputation: 56755
As indicated in the doc for .OpenTextFile
here, there is an optional ioMode parameter that sets the mode
of the opened file. The doc never specifies, but it appears that default is ForReading
which naturally will not allow you to (re)write nor append to the file.
Either way, just set the ioMode paramneter specifically to what you need.
Upvotes: 3