PDA

View Full Version : Solved: Close workbook



slamet Harto
01-21-2009, 06:12 AM
Hi guys

Refer to KB Entries by XLD to "Check If a File Is Already Open". I want to close the workbook that name AAA.XLS, while the active workbook is "BBB.XLS"

The following code is under BBB.XLS
Dim XLS as String
'this line refer range F4 where the value is AAA.XLS
XLS = ThisWorkbook.Path & Application.PathSeparator & [F4].Value

If IsFileOpen(XLS) Then
Workbooks.Close '<<< need advise to close the AAA.XLS only
End If


Function IsFileOpen(FileName As String)
Dim iFilenum As Long
Dim iErr As Long

On Error Resume Next
iFilenum = FreeFile()
Open FileName For Input Lock Read As #iFilenum
Close iFilenum
iErr = Err
On Error GoTo 0

Select Case iErr
Case 0: IsFileOpen = False
Case 70: IsFileOpen = True
Case Else: Error iErr
End Select
End Function


Many thanks in advance.
Rgds, Harto

xld
01-21-2009, 06:38 AM
That routine is really to check whether a file is open anywhere. If you just want to close it if you have it open, then use



Dim XLS As String
'this line refer range F4 where the value is AAA.XLS
XLS = Range("F4").Value

On Error Resume Next
Workbooks(XLS).Close
On Error GoTo 0

slamet Harto
01-21-2009, 09:33 PM
Hi Bob

Work well, Thank you so much.

If Dir$(XLS) <> "" Then
Workbooks(XLS).Close