Consulting

Results 1 to 3 of 3

Thread: activate opened workbook

  1. #1
    VBAX Newbie
    Joined
    Jul 2017
    Posts
    2
    Location

    activate opened workbook

    hello, I would like to activate opened workbook. My idea is folloving, but it doesn´t work. Can anyone help me ?

    Dim Fname As Double
    Dim Fname2 As Double


    Fname = "C:\file"
    Fname2 = "C:\file 2"


    If IsFileOpen("Fname") = True Then Workbooks(Fname).Activate


    ElseIf IsFileOpen("Fname2") = True Then Workbooks(Fname2).Activate


    Else: MsgBox ("Open certain files")


    End If

  2. #2
    Administrator
    VP-Knowledge Base
    VBAX Grand Master mdmackillop's Avatar
    Joined
    May 2004
    Location
    Scotland
    Posts
    14,489
    Location
    Don't save files on the Root drive (C :. Windows doesn't like it.
    Nearest to your code:
    Sub Test()
        Dim Fname As String
        Dim Fname2 As String
        Dim Fld As String
    
    
        Fld = "C:\VBAX\"
        Fname = "file.xlsx"
        Fname2 = "file 2.xlsx"
        If IsFileOpen(Fld & Fname) = True Then
            Workbooks(Fname).Activate
        ElseIf IsFileOpen(Fld & Fname2) = True Then
            Workbooks(Fname2).Activate
        Else: MsgBox "Open certain files"
        End If
    End Sub
    
    
    Function IsFileOpen(FileName As String)
        'http://www.vbaexpress.com/kb/getarticle.php?kb_id=468
        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
    MVP (Excel 2008-2010)

    Post a workbook with sample data and layout if you want a quicker solution.


    To help indent your macros try Smart Indent

    Please remember to mark threads 'Solved'

  3. #3
    VBAX Newbie
    Joined
    Jul 2017
    Posts
    2
    Location
    Thank you so much. It works very well.

Posting Permissions

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