Consulting

Results 1 to 2 of 2

Thread: test if text file is open

  1. #1
    VBAX Master
    Joined
    Jun 2006
    Posts
    1,091
    Location

    test if text file is open

    I use a text file in my program to create a logfile as the program runs to help me debug it. However, sometimes it is left open and then when it tries to reopen it crashes. Here is the code that I use to open it:

    [VBA]Dim logFile As String

    logFile = "H:\@Temp\Daniel B\Log Files\" & Environ("UserName") & "_LogFile.txt"

    FileNumber = FreeFile ' Get unused fileno
    'Create file name.
    Open logFile For Append As #FileNumber[/VBA]

    How can I test to see if it is open first? I know how to do it with a word file and an excel file but I tried to figure that out but it is completely different.

  2. #2
    One possiblity would be to check if it errors and report it. Maybe a function like

    Private Function IsFileOK(FullPath As String) As Boolean
    Dim f As Integer
    IsFileOK = True
    On Error GoTo FileProblem
    f = FreeFile
    Open FullPath For Append As #f
    Close #f
    Exit Function
    FileProblem:
    IsFileOK = False
    End Function
    used like
    If IsFileOK(logfile) Then
        filenumber = FreeFile
        Open logfile For Append As #filenumber
        ' ...
        Close #filenumber
    Else
    MsgBox ("Can not access file")
    End If

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •