Check to See if File is Open

Check to See if File is Open

When working with files it is important to know whether a file is open. This function will take care of things for you.

[vb autolinks=”false” classname=”myclass” collapse=”false” firstline=”1″ gutter=”true” highlight=”” htmlscript=”false” light=”false” padlinenumbers=”false” smarttabs=”true” tabsize=”4″ toolbar=”true” title=”Is File Open?”]
Function AlreadyOpen(sFileName As String) As Boolean
Dim wkb As Workbook
On Error Resume Next
Set wkb = Workbooks(sFileName )
AlreadyOpen = Not wkb Is Nothing
Set wkb = Nothing
End Function
[/vb]
To use the function you would pass to it the name of the workbook you want to check, in the following manner:
[vb autolinks=”false” classname=”myclass” collapse=”false” firstline=”1″ gutter=”true” highlight=”” htmlscript=”false” light=”false” padlinenumbers=”false” smarttabs=”true” tabsize=”4″ toolbar=”true” title=”Function Use”]
sFileName = "MyFileName.xls" ‘The file you want to check
sFilePath = "C:\MyFolder\MySubFolder\" ‘The file’s location
If AlreadyOpen(sFileName) Then
‘Do not have to open
Else
Workbooks.Open sFilePath & sFileName
End If
[/vb]