Okay, try this:
(note the correction I've made to the original AnyFileLocked function, too)
Sub Test()
Dim stDir As String
stDir = ThisWorkbook.Path
If AnyFileLockedSub(stDir) Then
MsgBox "File(s) open in " & stDir, vbCritical + vbOKOnly, "Error"
Exit Sub
End If
'continue...
Debug.Print "No locked files"
End Sub
Function AnyFileLockedSub(stDirectory As String)
Dim fso As Object
Dim fo, sf
If Not Right(stDirectory, 1) = "\" Then stDirectory = stDirectory & "\"
On Error Resume Next
Set fso = CreateObject("Scripting.FileSystemObject")
Set fo = fso.GetFolder(stDirectory)
If Not fo Is Nothing Then
For Each sf In fo.SubFolders
AnyFileLockedSub = AnyFileLocked(stDirectory & sf)
If AnyFileLockedSub Then Exit Function
Next sf
End If
AnyFileLockedSub = AnyFileLocked(stDirectory)
End Function
Function AnyFileLocked(stDirectory As Variant) As Boolean
Dim sFN As Variant
If Not Right(stDirectory, 1) = "\" Then stDirectory = stDirectory & "\"
sFN = Dir(stDirectory)
While sFN <> ""
Debug.Print "Checking " & stDirectory & sFN
If FileLocked(stDirectory & sFN) And sFN <> ThisWorkbook.Name Then
AnyFileLocked = True
Exit Function
End If
sFN = Dir
Wend
End Function
Function FileLocked(stFileName As Variant) As Boolean
On Error Resume Next
Open stFileName For Binary Access Read Write Lock Read Write As #1
Close #1
If Err.Number Then
FileLocked = True
Err.Clear
Else
FileLocked = False
End If
End Function
Bookmarks