Consulting

Results 1 to 3 of 3

Thread: Solved: Close workbook

  1. #1
    VBAX Tutor
    Joined
    Sep 2007
    Posts
    265
    Location

    Solved: Close workbook

    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
    [VBA]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
    [/VBA]

    Many thanks in advance.
    Rgds, Harto

  2. #2
    Distinguished Lord of VBAX VBAX Grand Master Bob Phillips's Avatar
    Joined
    Apr 2005
    Posts
    25,453
    Location
    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

    [vba]

    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
    [/vba]
    ____________________________________________
    Nihil simul inventum est et perfectum

    Abusus non tollit usum

    Last night I dreamed of a small consolation enjoyed only by the blind: Nobody knows the trouble I've not seen!
    James Thurber

  3. #3
    VBAX Tutor
    Joined
    Sep 2007
    Posts
    265
    Location
    Hi Bob

    Work well, Thank you so much.

    [VBA]If Dir$(XLS) <> "" Then
    Workbooks(XLS).Close[/VBA]

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •