paul.robinson@it-tallaght.ie
Guest
Re: check if a file is open
Hi
WBFullName is the full path to the file. WBFileName gets the name of
the file. The functions IsFileOpen and IsWorkBookOpen decide if the
file is open on another or your machine.
WBFileName = GetFileName(WBFullName)
If IsFileOpen(WBFullName) Then 'if someone has it open on network
If Not IsWorkBookOpen(WBFileName) Then 'if that someone isn't
you
MsgBox "This file is in use by another user"
Else
MsgBox "You have it open already!"
End If
Else
'open it etc
End If
Uses the functions:
'See Green p80
'Returns the full file name from the end of a path by looking for first
\
'If no \, returns the file name
Public Function GetFileName(FullPathString As String) As String
Dim stPathSep As String 'Path separator, \
Dim FPLength As Integer 'length of FullPathString
Dim i As Integer 'counter
stPathSep = Application.PathSeparator
FPLength = Len(FullPathString)
For i = FPLength To 1 Step -1
If Mid(FullPathString, i, 1) = stPathSep Then Exit For
Next i
GetFileName = Right(FullPathString, FPLength - i)
End Function
'Lifted from Microsoft KB
' This function checks to see if a file is open or not. If the file is
' already open, it returns True. If the file is not open, it returns
' False. Otherwise, a run-time error will occur because there is
' some other problem accessing the file.
Function IsFileOpen(filename As String)
Dim filenum As Integer, errnum As Integer
Err.Clear
On Error Resume Next ' Turn error checking off.
filenum = FreeFile() ' Get a free file number.
' Attempt to open the file and lock it.
Open filename For Input Lock Read As #filenum
Close filenum ' Close the file.
errnum = Err ' Save the error number that occurred.
On Error GoTo 0 ' Turn error checking back on.
' Check to see which error occurred.
Select Case errnum
' No error occurred.
' File is NOT already open by another user.
Case 0
IsFileOpen = False
' Error number for "Permission Denied."
' File is already opened by another user.
Case 70
IsFileOpen = True
' Another error occurred.
Case Else
IsFileOpen = False
End Select
End Function
'See Green p81
Function IsWorkBookOpen(WorkBookName As String) As Boolean
Dim Wkb As Workbook
On Error Resume Next
Set Wkb = Workbooks(WorkBookName)
If Not Wkb Is Nothing Then
IsWorkBookOpen = True
End If
Set Wkb = Nothing
End Function
regards
Paul
Bookmarks