Frederico
Frederico

Reputation: 25

VBA Error 52 to read last line of log file

I am using this code to open a log file, and read the last line, to see if the file was correctly closed last time or not. If not, it will add a line in the log specifying a "Fatal Error". But, when the code runs, I get an Error 52 message. I already read a lot of posts here and other foruns, changed my code and used some posted here to make it work, but nothing worked.

Edited to better MCVE:

Public Function WriteLogFile(strMsg As String)

Const LogFileName As String = "\log\FrenteCaixa.log"

Dim FileNum As Integer, strLogMsg As String, strAddFatalError As String
FileNum = FreeFile

If Right(strMsg, 6) = "aberto" Then
    Open ThisWorkbook.Path & LogFileName For Input Access Read Lock Read As #FileNum
        Dim lngCounter As Long, strLastLine As String
        lngCounter = 0
        Do Until EOF(lngCounter) **--> THE ERROR IS HERE!**
            Line Input #FileNum, strLastLine
            If Left(strLastLine, 8) <> "<!-- EoF" Then strAddFatalError = "<!-- FATAL ERROR -->"
            lngCounter = lngCounter + 1
        Loop
    Close #FileNum
End If

Open ThisWorkbook.Path & LogFileName For Append As #FileNum
If strAddFatalError <> "" Then Print #FileNum, strAddFatalError
Print #FileNum, strLogMsg
Close #FileNum

End Function

Upvotes: 0

Views: 146

Answers (1)

Inarion
Inarion

Reputation: 608

Your usage of EOF(lngCounter) is wrong. From its documentation, this function expects a file number:

Function EOF(FileNumber As Integer) As Integer

You are feeding it with a line counter, which is 0 at the start. This might be the reason for the error you are seeing.

Try replacing EOF(lngCounter) with EOF(FileNum) and see if it works.


Also, if I'm not mistaken, you don't need that line counter lngCounter at all here. Reading a line via Line Input will advance the line pointer so that the next time the statement is executed, it will read the next line.

Public Sub WriteLogFile(strMsg As String)

    Const LogFileName As String = "\log\FrenteCaixa.log"

    Dim FileNum As Integer, strLogMsg As String, strAddFatalError As String
    FileNum = FreeFile

    If Right(strMsg, 6) = "aberto" Then
        Open ThisWorkbook.Path & LogFileName For Input Access Read Lock Read As #FileNum
        Dim strLastLine As String
        Do Until EOF(FileNum)                 '**--> THE ERROR IS HERE!**
            Line Input #FileNum, strLastLine
            If Left(strLastLine, 8) <> "<!-- EoF" Then strAddFatalError = "<!-- FATAL ERROR -->"
        Loop
        Close #FileNum
    End If

    Open ThisWorkbook.Path & LogFileName For Append As #FileNum
    If strAddFatalError <> "" Then Print #FileNum, strAddFatalError
    Print #FileNum, strLogMsg
    Close #FileNum

End Sub

I've also made it a Sub as you're not assigning any return value, so having it as a function would be somewhat misleading.

Upvotes: 2

Related Questions