VBA – Determine the state of a file, Is a file already open

Ever needed to determine if an Excel Workbook was already open, perhaps a Word document. The little function below can help you determine the state of a file.

'---------------------------------------------------------------------------------------
' Procedure : fGetFileState
' Author    : Daniel Pineault, CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Determine the current state of a given file
' Copyright : The following may be altered and reused as you wish so long as the
'             copyright notice is left unchanged (including Author, Website and
'             Copyright).  It may not be sold/resold or reposted on other sites (links
'             back to this site are allowed).
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' sFile     - Full path and filename with extension to determine the state of
'
' Usage:
' ~~~~~~
' fGetFileState("C:\Databases\testme.xlsm")
'
' Revision History:
' Rev       Date(yyyy/mm/dd)        Description
' **************************************************************************************
' 1         2009-Oct-09             Initial Release
'---------------------------------------------------------------------------------------
Function fGetFileState(sFile As String) As String
    On Error GoTo Error_Handler
    Dim iFileNo         As Integer
 
    iFileNo = FreeFile
    Open sFile For Input Lock Read As iFileNo
    Close iFileNo
 
Error_Handler_Exit:
    On Error Resume Next
    If fGetFileState = vbNullString Then fGetFileState = "File is not open"
    Exit Function
 
Error_Handler:
    Select Case Err.Number
        Case 53
            fGetFileState = "File does not exist"
        Case 70
            fGetFileState = "Permission denied - File is already open"
        Case 76
            fGetFileState = "Path not found"
        Case Else
            fGetFileState = "Unknow State"
    End Select
    GoTo Error_Handler_Exit
End Function

View ratings
Rate this article

Share and Enjoy

  • Google Plus
  • Facebook
  • LinkedIn
  • Twitter
  • Email
  • Print

Leave a Reply










Email
Print
WP Socializer Aakash Web