Check if excel is open vba

In VBA, I opened an MS Excel file named «myWork.XL» programmatically.

Now I would like a code that can tell me about its status — whether it is open or not. I.e. something like IsWorkBookOpened("myWork.XL) ?

Andrei Konstantinov's user avatar

asked Feb 21, 2012 at 6:19

user1222679's user avatar

0

Try this:

Option Explicit

Sub Sample()
    Dim Ret

    Ret = IsWorkBookOpen("C:myWork.xlsx")

    If Ret = True Then
        MsgBox "File is open"
    Else
        MsgBox "File is Closed"
    End If
End Sub

Function IsWorkBookOpen(FileName As String)
    Dim ff As Long, ErrNo As Long

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

    Select Case ErrNo
    Case 0:    IsWorkBookOpen = False
    Case 70:   IsWorkBookOpen = True
    Case Else: Error ErrNo
    End Select
End Function

Tim Cooper's user avatar

Tim Cooper

156k38 gold badges330 silver badges278 bronze badges

answered Feb 21, 2012 at 7:48

Siddharth Rout's user avatar

Siddharth RoutSiddharth Rout

146k17 gold badges206 silver badges250 bronze badges

12

For my applications, I generally want to work with a workbook rather than just determine if it’s open. For that case, I prefer to skip the Boolean function and just return the workbook.

Sub test()

    Dim wb As Workbook

    Set wb = GetWorkbook("C:UsersdickDropboxExcelHoops.xls")

    If Not wb Is Nothing Then
        Debug.Print wb.Name
    End If

End Sub

Public Function GetWorkbook(ByVal sFullName As String) As Workbook

    Dim sFile As String
    Dim wbReturn As Workbook

    sFile = Dir(sFullName)

    On Error Resume Next
        Set wbReturn = Workbooks(sFile)

        If wbReturn Is Nothing Then
            Set wbReturn = Workbooks.Open(sFullName)
        End If
    On Error GoTo 0

    Set GetWorkbook = wbReturn

End Function

answered Feb 21, 2012 at 17:18

Dick Kusleika's user avatar

Dick KusleikaDick Kusleika

32.5k4 gold badges51 silver badges73 bronze badges

6

If its open it will be in the Workbooks collection:

Function BookOpen(strBookName As String) As Boolean
    Dim oBk As Workbook
    On Error Resume Next
    Set oBk = Workbooks(strBookName)
    On Error GoTo 0
    If oBk Is Nothing Then
        BookOpen = False
    Else
        BookOpen = True
    End If
End Function

Sub testbook()
    Dim strBookName As String
    strBookName = "myWork.xls"
    If BookOpen(strBookName) Then
        MsgBox strBookName & " is open", vbOKOnly + vbInformation
    Else
        MsgBox strBookName & " is NOT open", vbOKOnly + vbExclamation
    End If
End Sub

answered Feb 21, 2012 at 8:44

Charles Williams's user avatar

Charles WilliamsCharles Williams

23.1k5 gold badges37 silver badges38 bronze badges

2

I would go with this:

Public Function FileInUse(sFileName) As Boolean
    On Error Resume Next
    Open sFileName For Binary Access Read Lock Read As #1
    Close #1
    FileInUse = IIf(Err.Number > 0, True, False)
    On Error GoTo 0
End Function

as sFileName you have to provide direct path to the file for example:

Sub Test_Sub()
    myFilePath = "C:UsersUserNameDesktopexample.xlsx"
    If FileInUse(myFilePath) Then
        MsgBox "File is Opened"
    Else
        MsgBox "File is Closed"
    End If
End Sub

answered Mar 10, 2014 at 19:39

user2267971's user avatar

user2267971user2267971

3631 gold badge4 silver badges12 bronze badges

What if you want to check without creating another Excel instance?

For example, I have a Word macro (which is run repeatedly) that needs to extract data from an Excel spreadsheet. If the spreadsheet is already open in an existing Excel instance, I would prefer not to create a new instance.

I found a great answer here that I built on:
http://www.dbforums.com/microsoft-access/1022678-how-check-wether-excel-workbook-already-open-not-search-value.html

Thanks to MikeTheBike and kirankarnati

Function WorkbookOpen(strWorkBookName As String) As Boolean
    'Returns TRUE if the workbook is open
    Dim oXL As Excel.Application
    Dim oBk As Workbook

    On Error Resume Next
    Set oXL = GetObject(, "Excel.Application")
    If Err.Number <> 0 Then
        'Excel is NOT open, so the workbook cannot be open
        Err.Clear
        WorkbookOpen = False
    Else
        'Excel is open, check if workbook is open
        Set oBk = oXL.Workbooks(strWorkBookName)
        If oBk Is Nothing Then
            WorkbookOpen = False
        Else
            WorkbookOpen = True
            Set oBk = Nothing
        End If
    End If
    Set oXL = Nothing
End Function

Sub testWorkbookOpen()
    Dim strBookName As String
    strBookName = "myWork.xls"
    If WorkbookOpen(strBookName) Then
        msgbox strBookName & " is open", vbOKOnly + vbInformation
    Else
        msgbox strBookName & " is NOT open", vbOKOnly + vbExclamation
    End If
End Sub

answered Aug 9, 2013 at 7:19

Derek Johnson's user avatar

Derek JohnsonDerek Johnson

9271 gold badge11 silver badges15 bronze badges

This one is a bit easier to understand:

Dim location As String
Dim wbk As Workbook

location = "c:excel.xls"

Set wbk = Workbooks.Open(location)

'Check to see if file is already open
If wbk.ReadOnly Then
  ActiveWorkbook.Close
    MsgBox "Cannot update the excelsheet, someone currently using file. Please try again later."
    Exit Sub
End If

answered Jul 9, 2013 at 14:26

Bulki's user avatar

BulkiBulki

7341 gold badge10 silver badges30 bronze badges

1

Checkout this function

'********************************************************************************************************************************************************************************
'Function Name                     : IsWorkBookOpen(ByVal OWB As String)
'Function Description             : Function to check whether specified workbook is open
'Data Parameters                  : OWB:- Specify name or path to the workbook. eg: "Book1.xlsx" or "C:UsersKannan.SDesktopBook1.xlsm"

'********************************************************************************************************************************************************************************
Function IsWorkBookOpen(ByVal OWB As String) As Boolean
    IsWorkBookOpen = False
    Dim WB As Excel.Workbook
    Dim WBName As String
    Dim WBPath As String
    Err.Clear
    On Error Resume Next
    OWBArray = Split(OWB, Application.PathSeparator)
    Set WB = Application.Workbooks(OWBArray(UBound(OWBArray)))
    WBName = OWBArray(UBound(OWBArray))
    WBPath = WB.Path & Application.PathSeparator & WBName
    If Not WB Is Nothing Then
        If UBound(OWBArray) > 0 Then
            If LCase(WBPath) = LCase(OWB) Then IsWorkBookOpen = True
        Else
            IsWorkBookOpen = True
        End If
    End If
    Err.Clear
End Function

answered Nov 14, 2013 at 16:33

Kannan Suresh's user avatar

Kannan SureshKannan Suresh

4,5933 gold badges34 silver badges59 bronze badges

5

Home / VBA / VBA Check IF a Workbook is Open (Excel File)

To check if a workbook is open using a VBA code, you need to use FOR EACH loop that can loop through all the workbooks that are open at the moment and verify each workbook’s name with the name you have mentioned. You can use a message box to get the result of the loop. Or you can also make the code to enter the result in a cell.

  1. First, you need to declare variables to use in the code to create a loop.
    1-create-a-loop
  2. Use an input box to get the name of the workbook that you wish to search for.
    2-use-an-input-box
  3. Start the loop to loop through all the open workbooks.
    3-start-the-loop-to-loop
  4. Write code with IF STATEMENT to verify the name of the workbook with the name you have entered in the input box, and once the name matches, activates the workbook, show a message box that workbook is found, and exit the procedure.
    4-code-with-if-statement
  5. In the end, end the loop and use a message box to show a message box if nothing has been found.
    5-end-the-loop-and-use-amessage-box

Helpful Links: Run a Macro – Macro Recorder – Visual Basic Editor – Personal Macro Workbook

Here’s the full code.

Sub vba_check_workbook()

Dim WB As Workbook
Dim myWB As String

myWB = InputBox(Prompt:="Enter the workbook name.")

For Each WB In Workbooks
    If WB.Name = myWB Then
        WB.Activate
        MsgBox "Workbook Found!"
        Exit Sub
    End If
Next WB

MsgBox "Not Found"

End Sub

More on VBA Workbooks

VBA Save Workbook | VBA Close Workbook | VBA Delete Workbook | VBA ThisWorkbook | VBA Rename Workbook | VBA Activate Workbook | VBA Combine Workbook | VBA Protect Workbook (Unprotect) | VBA Open Workbook | VBA Check IF an Excel Workbook Exists in a Folder| VBA Create New Workbook (Excel File)

  • VBA Workbook

This tutorial shows how to check if a specific workbook is open through the use of VBA

METHOD 1. Check if workbook is open in the same Excel session

VBA

Sub Check_if_workbook_is_open()

‘declare a variable
Dim wb As Workbook

For Each wb In Workbooks

If wb.Name = «Parameters.xlsx» Then

‘this message will appear if one of the open workbooks is Parameters.xlsx
MsgBox «File is Open»

End If

Next

End Sub

ADJUSTABLE PARAMETERS
File Name: Select the file name of a workbook that you want to check if it’s open by changing the file name «Parameters.xlsx» in the VBA code.
Message: Select the message that you want to be displayed if the workbook is open by changing the message «File is Open» in the VBA code.

ADDITIONAL NOTES
Note 1: This VBA code will check Excel workbooks in the same session as the workbook from which you are running this VBA code.

METHOD 2. Check if workbook is open across all Excel sessions

VBA

Sub Check_if_workbook_is_open()

‘declare a variable
Dim FilePath As String

FilePath = IsWBOpen(«C:ExcelParameters.xlsx»)

If FilePath = True Then

MsgBox «File is Open»

Else

MsgBox «File is Closed»

End If

End Sub

Function IsWBOpen(FileName As String)

‘declare variables
Dim FileNo As Long
Dim ErrorNo As Long

On Error Resume Next
FileNo = FreeFile()

Open FileName For Input Lock Read As #FileNo
Close FileNo

ErrorNo = Err

On Error GoTo 0

Select Case ErrorNo

Case 0
IsWBOpen = False

Case 70
IsWBOpen = True

Case Else
Error ErrorNo

End Select

End Function

ADJUSTABLE PARAMETERS
File Path and Name: Select the file path, including the name of the file, by changing «C:ExcelParameters.xlsx» in the VBA code.
Message if Workbook is Open: Select the message that you want to be displayed if the workbook is open by changing the message «File is Open» in the VBA code.
Message if Workbook is Closed: Select the message that you want to be displayed if the workbook is closed by changing the message «File is Closed» in the VBA code.

ADDITIONAL NOTES
Note 1: This VBA code will check workbooks in all Excel sessions.
Note 2: This method creates a User Defined Function called ‘IsWBOpen’ and then runs the VBA code.

Explanation about how to check if workbook is open

EXPLANATION

EXPLANATION
This tutorial shows how to check if a specific workbook is open in the same Excel session or across all Excel sessions, using VBA.

The first method shows how to check if a workbook, with a specific name, is open in the same Excel session in which the VBA code is run. The second method shows how to check if a specific workbook, including its location and name, is open in all Excel sessions. This is achieved by creating a User Defined Function and then applying this in a macro.

Related Topic Description Related Topic and Description
Check if workbook is open, if closed open workbook How to check if a specific workbook is open and if it’s closed then open the workbook using VBA
Open an Excel workbook How to open a single workbook using Excel, VBA and Shortcut
Open an Excel workbook as Read-Only How to open a single workbook as Read-Only using Excel and VBA

This Excel tutorial explains how to use Workbooks Open Method to open a closed workbook and check if workbook is opened.

In worksheet automation, we may need to programmatically open another workbook to change data based on the active workbook. Workbooks Open Method is very straight forward to use, you just need to specify the file name to open, but there are many other optional parameters you may want to use.

Note that Workbooks Open Method is different from Workbook Open Event, the latter is to trigger VBA when a workbook is opened.

Example of Excel VBA Workbooks Open Method

Assume that you have two workbooks. One is called FileA.xlsm, another is called FileB.xlsx

Now you want to open FileB from FileA, so FileA should contain the Macro (therefore .xlsm) and FileB does not need any Macro.

In FileA, create a Sub in Module and insert the below code, which will open FileB.

Workbooks.Open ("C:UsersWYMANDesktopfolderFileB.xlsx")

After you open FileB, you may need to change the data.  Therefore you need to give FileB a name in order to manipulate it.

The below code give FileB a name called masterWB.

Set masterWB = Workbooks.Open("C:UsersWYMANDesktopfolderFileB.xlsx")

If the FileB is already opened, you will receive an alert.

Now you can manipulate FileA (using thisworkbook) and FileB(using masterWB) from FileA

masterWB.Sheets("Sheet1").Range("A1").Value = "FileB"
ThisWorkbook.Sheets("Sheet1").Range("A1").Value = "FileA"

Check if Workbook is opened already

You may already have FileB opened before the Macro is run, in that case you will receive an alert message if you use Workbooks.Open, this will prevent your Macro from further running.

workbooks_open

There are some methods to test if a Workbook is already opened, below is my preferred method. This Function loop through  all currently opened Workbook to see if there is a Workbook name same as the name provided in the Function argument.

Public Function wIfWbOpen(wbName As String) As Boolean
    Dim oWB As Excel.Workbook
    wIfWbOpen = False
    For Each oWB In Application.Workbooks
        If oWB.Name = wbName Then
            wIfWbOpen = True
            Exit For
        End If
    Next
    Set oWB = Nothing
End Function

Finally use the Function in the Sub in which you want to run code in FileB.

Public Sub updateData()
    If wIfWbOpen("FileB.xlsx") Then
        Set masterWB = Workbooks("FileB.xlsx")
    Else
        Set masterWB = Workbooks.Open("C:UsersWYMANDesktopfolderFileB.xlsx")
    End If
End Sub

Outbound References

http://www.ozgrid.com/forum/showthread.php?t=63350

When writing code in Excel VBA it is a good practice to first check for some conditions before taking certain actions. For example, when we write code to copy data to or from a range in an Excel file, it is important that we first check if the file is open. We can include a statement that opens the file in case it is closed.

In this tutorial we will look at 2 methods we can use to apply Excel VBA in checking whether a workbook is open or closed.

Method 1: Use a User Defined Function (UDF)

Excel VBA does not have an in-built function for checking whether files are open or not, but we can create a UDF to do the task. The UDF returns TRUE if the file is open and FALSE if it is not open.

Create the UDF

We use the following steps to create the UDF:

  1. In the active worksheet press Alt + F11 to open the Visual Basic Editor (VBE). Alternatively, click Developer >> Code >> Visual Basic.

  1. In the Project Window right-click the ThisWorkbook object and select Insert >> Module on the shortcut menu>

Alternatively, we click Insert >> Module on the menu bar.

  1. In the inserted module, type the following function procedure:

Function IsWorkBookOpen(Name As String) As Boolean

    Dim xlWb As Workbook

    On Error Resume Next

    Set xlWb = Application.Workbooks.Item(Name)

    IsWorkBookOpen = (Not xlWb Is Nothing)

End Function

  1. Save the function procedure and save the workbook as a macro-enabled workbook.

Explanation of the User-Defined Function

Function IsWorkBookOpen(Name As String) As Boolean.

The function returns a value of Boolean data type. This means that it returns either a TRUE or FALSE value. The function takes one argument of the String data type.

One Workbook object variable is declared.

If an error occurs, this statement instructs VBA to continue executing the statements immediately after the statement that caused the error.

The workbook to be checked is assigned to the workbook variable.

IsWorkBookOpen = (Not xlWb Is Nothing).

This statement checks if the workbook variable has a workbook object and returns TRUE if it has one or FALSE if it is empty.

The TRUE or FALSE value is assigned to the IsWorkBookOpen variable and this is the value that is returned by the function.

Use the UDF

We can now use our UDF by calling it in a subroutine by using the following steps:

  1. Press Alt + F11 to open the Visual Basic Editor.
  2. Insert a new module and type in the Sub procedure below:

Sub checkIfFileOpen()

    Dim xlCheck As Boolean

    Dim myWB As String

    myWB = InputBox(Prompt:=«Enter the name of the workbook.»)

    xlCheck = IsWorkBookOpen(myWB)

    If xlCheck Then

        MsgBox «The file is open», vbInformation

    Else

        MsgBox «The file is not open», vbInformation

    End If

End Sub

  1. Save the Sub procedure and save the workbook as a macro-enabled workbook.
  2. Place the cursor anywhere in the Sub procedure and press F5 to run the code.
  3. In the Input box that pops up, enter the name of the workbook that we want to check if it is open or closed and click OK. In this case, we have entered the name Suppliers of a closed workbook.

A message box pops up displaying the message that the workbook is not open.

When we open the Suppliers workbook and run the procedure again, the message box pops displaying the message that the file is open.

Explanation of the Sub procedure

  • Two variables are declared, one of Boolean data type and the other of String data type.
  • The InputBox function prompts for the name of the workbook.
  • The name of the workbook is assigned to the myWB variable.
  • The value in the myWB variable is passed to the IsWorkbookOpen function which returns TRUE if the file is open or FALSE if it is not open. Either of these values is assigned to the xlCheck variable.
  • If the value in the xlCheck variable is TRUE, the MsgBox function sends a message box to the screen which displays the message The file is open. If the value in the xlCheck variable is FALSE, the MsgBox function sends to the screen a message box that displays the information The file is not open.

Method 2: Use a Sub procedure

We can also use a Sub procedure to check if a workbook is open or closed in Excel by using the following steps:

  1. Press Alt + F11 to open the Visual Basic Editor and insert a new module.
  2. In the module type the following Sub procedure:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

Sub checkWB()

Dim WB As Workbook

Dim myWB As String

myWB = InputBox(Prompt:=«Enter the workbook name.»)

For Each WB In Workbooks

    If WB.Name = myWB Then

        WB.Activate

        MsgBox «Workbook Is Open!»

        Exit Sub

    End If

Next WB

MsgBox «Workbook is not open»

End Sub

  1. Save the Sub procedure and save the workbook as a macro-enabled workbook.
  2. Place the cursor anywhere in the procedure and press F5 to run the procedure.
  3. In the Input box that pops up, enter the name of the workbook that we want to check if it is open or closed and click OK. In this case, we have entered the name Suppliers.xlsx of a closed workbook.

The message box displaying the information that the workbook is not open pops up on the screen.

If we open the Suppliers workbook and run the procedure again, the message box that displays the information that the workbook is open pops up on the screen.

Explanation of the subroutine

  • A workbook variable and a string variable are declared.
  • The InputBox function prompts the user for the name of the file that is to be checked.
  • The input from the user is assigned to the myWB variable.
  • For Each Next construct loops through all the open workbooks checking the value in the myWB variable against each of the names of the open workbooks collection.
  • If a match is found, the relevant open workbook is activated and the MsgBox function sends a message box to the screen displaying the message Workbook is Open!, and the Subroutine is exited.
  • If a match is not found, the MsgBox function sends a message box to the screen that displays the information that the Workbook is not open and the subroutine ends.

Conclusion

In this tutorial, we have explored two methods that we can use to check if a file is open or closed in Excel.

The first method involves the use of a User Defined Function and the second method applies a subroutine.

Ezoic

Post Views: 211

  • Remove From My Forums
  • Question

  • Hello Developers

    I am using following code in workbook A to open workbook B  and than run some code. Issue happens when workbook B is already open. I want to check if workbook B is open than do something and if it is close than do something

    dim wbdata as workbook

    Set wbDATA = Workbooks.Open(ThisWorkbook.Path & «filename.xlsx»)

    »»’some code that make changes to wbDATA

    Thanks.

    • Edited by

      Monday, May 5, 2014 6:14 PM

Answers

  • Adapt the following

    Sub test()
    Dim bWasOpen As Boolean
    Dim path As String, file As String
    Dim wb As Workbook
    
        path = ThisWorkbook.path & ""
        file = "filename.xlsx"
    
        If GetOrOpenWB(wb, path, file, bWasOpen) Then
            'do stuff,  'when done
            If bWasOpen Then
                ' does the user want to keep it open ?
            Else
                wb.Close savechanges:=True    ' or false
            End If
            'problem to open the file, read only?
        End If
    
    End Sub
    
    Function GetOrOpenWB(wb As Workbook, path As String, file As String, bWasOpen As Boolean) As Boolean
    
        On Error Resume Next
        Set wb = Workbooks(file)
        On Error GoTo errH:
        If Not wb Is Nothing Then
            bWasOpen = True
        Else
            Set wb = Workbooks.Open(path & file)
        End If
        GetOrOpenWB = Not wb Is Nothing
        Exit Function
    errH:
        MsgBox Err.Description
    End Function
    

    • Marked as answer by
      zaveri cc
      Friday, May 9, 2014 7:15 PM

Открыта или закрыта книга Excel? Проверяем с помощью кода VBA по краткому или полному имени файла, используя объектную переменную, цикл или оператор Open.

Проверка по краткому имени

Способ проверки по краткому имени, открыта ли рабочая книга, позволяет определить состояние проверяемой книги в том же экземпляре приложения Excel, в котором открыта книга с проверяющим кодом.

Использование объектной переменной

Вариант пользовательской функция VBA Excel, предназначенной для проверки, открыта или закрыта рабочая книга, путем определения результата присвоения ссылки на нее объектной переменной. Присвоение состоялось (BookOpenClosed = True) – книга открыта, произошла ошибка и присвоение не состоялось (BookOpenClosed = False) – книга закрыта.

Function BookOpenClosed(wbName As String) As Boolean

    Dim myBook As Workbook

    On Error Resume Next

        Set myBook = Workbooks(wbName)

    BookOpenClosed = Not myBook Is Nothing

End Function

Аргумент функции:

  • wbName – краткое имя проверяемой рабочей книги.

Перебор открытых книг циклом

Этот вариант функции BookOpenClosed перебирает с помощью цикла все открытые книги Excel и проверяет их краткие имена на совпадение с кратким именем проверяемой книги. Совпадение найдено (BookOpenClosed = True) – книга открыта, совпадение не найдено (BookOpenClosed = False) – книга закрыта.

Function BookOpenClosed(wbName As String) As Boolean

    Dim myBook As Workbook

    For Each myBook In Workbooks

        If myBook.Name = wbName Then

            BookOpenClosed = True

            Exit For

        End If

    Next

End Function

В коллекцию Workbooks входят и скрытые книги, в том числе Личная книга макросов, и книга с функцией.

Проверка по полному имени

Проверка по полному имени с помощью оператора Open позволяет узнать, открыта ли рабочая книга каким-либо другим процессом: текущим экземпляром Excel, в котором открыта книга с проверяющим кодом, другим экземпляром Excel или сторонним приложением.

Function BookOpenClosed(wbFullName As String) As Boolean

    Dim ff As Integer

    ff = FreeFile

        On Error Resume Next

        Open wbFullName For Random Access Read Write Lock Read Write As #ff

        Close #ff

    BookOpenClosed = (Err.Number <> 0)

End Function

Аргумент функции:

  • wbFullName – полное имя проверяемой рабочей книги.

Эта функция открывает с помощью оператора Open файл проверяемой книги с разрешением чтения и записи (параметр access) и запретом чтения и записи, если этот файл уже открыт другим процессом (параметр lock).

Если файл уже открыт другим процессом, а указанный тип доступа (параметр access) не разрешен (параметр lock), операция открытия завершится с ошибкой, а выражение (Err.Number <> 0) возвратит значение True.

Примеры проверки состояния книги

По краткому имени

Sub Primer1()

    If BookOpenClosed(«Книга1.xlsx») Then

        MsgBox «Книга открыта»

    Else

        MsgBox «Книга закрыта»

    End If

End Sub

По полному имени

Sub Primer2()

    If BookOpenClosed(«C:Папка1Папка2Папка3Книга1.xlsx») Then

        MsgBox «Книга открыта»

    Else

        MsgBox «Книга закрыта»

    End If

End Sub


Хитрости »

4 Май 2011              93361 просмотров


Как проверить открыта ли книга?

Собственно суть темы отражена в названии. Как при выполнении кода из VBA узнать перед обращением к книге открыта она или нет? Ведь если книга закрыта, то обращение к ней вызовет ошибку, а если открывать без проверки — то это может повлечь за собой утерю данных, если предварительно эта книга не была сохранена. Ни один ни второй вариант, естественно, не устраивают. Я покажу два способа проверки через функции. Если функция вернет True — книга открыта, если False — закрыта. Для проверки функций используем проверочную процедуру Check_Open_Book:

Sub Check_Open_Book()
    If IsBookOpen("Книга1.xls") Then
        MsgBox "Книга открыта", vbInformation, "Сообщение"
    Else
        MsgBox "Книга закрыта", vbInformation, "Сообщение"
        'открываем книгу
        Workbooks.Open "C:Книга1.xls"
    End If
End Sub

Данная процедура вызывает функцию IsBookOpen, передавая ей в качестве параметра имя книги, «открытость» которой мы хотим проверить. Я приведу несколько вариантов самой функции IsBookOpen. Во всех вариантах действует один и тот же принцип: код любого из вариантов функции IsBookOpen необходимо скопировать и вставить в стандартный модуль. Модуль должен быть внутри той книги, в кодах которой планируется проверять открыта ли книга. Только тогда IsBookOpen будет доступна для вызова из любого кода этой же книги.
Если вдруг в момент выполнения на строке If IsBookOpen(«Книга1.xls») Then появится ошибка «Sub or function not defined» — значит функция IsBookOpen либо не была скопирована в стандартный модуль, либо она вообще не в стандартном модуле, а в модуле листа, формы или книги.


Вариант 1:

Function IsBookOpen(wbName As String) As Boolean
    Dim wbBook As Workbook
    For Each wbBook In Workbooks
        If wbBook.Name <> ThisWorkbook.Name Then
            If Windows(wbBook.Name).Visible Then
                If wbBook.Name = wbName Then IsBookOpen = True: Exit For
            End If
        End If
    Next wbBook
End Function

Функция просматривает все открытые книги и если находит среди них книгу с указанным именем, то функция возвращает True. Есть небольшая особенность — функция исключает скрытые книги(это либо надстройки, либо PERSONAL.XLS). Так же из просмотра исключена та книга, в которой расположен сам код. Если Вам нужно проверить наличие книги независимо от её видимости, то необходимо просто заменить блок

    If Windows(wbBook.Name).Visible Then
        If wbBook.Name = wbName Then IsBookOpen = True: Exit For
    End If

на одну строку(просто убрать лишнее условие проверки)

    If wbBook.Name = wbName Then IsBookOpen = True: Exit For

Либо можно использовать

Вариант 2:

Function IsBookOpen(wbName As String) As Boolean
    Dim wbBook As Workbook: On Error Resume Next
    Set wbBook = Workbooks(wbName)
    IsBookOpen = Not wbBook Is Nothing
End Function

Данный способ обращается к любой открытой книге, даже если она скрыта как PERSONAL.XLS или надстройка. Однако у данной функции есть недостаток — используется оператор On Error и если в настройках VBA(ToolsOptions -вкладка General) установлено Break on All Errors — то этот код не сработает, если книга не открыта — получим ошибку. В то время как Вариант1 с циклом по всем открытым книгам сработает без ошибок.


Вариант 3:

По просьбам читателей решил добавить код, который проверяет открыта ли книга независимо от её месторасположения и используемого приложения Excel. Книга может быть открыта другим пользователем (если книга на сервере), в другом экземпляре Excel или в этом же экземпляре Excel.

Function IsBookOpen(wbFullName As String) As Boolean
    Dim iFF As Integer, retval As Boolean
    iFF = FreeFile
    On Error Resume Next
    Open wbFullName For Random Access Read Write Lock Read Write As #iFF
    retval = (Err.Number <> 0)
    Close #iFF
    IsBookOpen = retval
End Function

Функция несколько отличается от приведенных выше — передается в неё не только имя книги, а полный путь к книге, включая имя и расширение:

Sub Test()
    MsgBox "Файл 'Книга1'" & IIf(IsBookOpen("C:Книга1.xls"), " уже открыт", " не занят")
End Sub

Или более близкий к жизненной ситуации вариант: надо открыть книгу, внести в книгу изменения, сохранить и закрыть. Если книга кем-то уже открыта — получим ошибку на этапе сохранения или запрос на этапе открытия. Поэтому сначала проверяем доступность книги и если она доступна — вносим изменения и сохраняем.

Sub Test()
    Dim sWBFullName As String
    Dim wb As Workbook
    'полный путь к проверяемой книге
    sWBFullName = "C:DocumentsКнига1.xls"
    'если книга кем-то открыта - пропускаем обработку этой книги
    'книга закрыта - вносим изменения, сохраняем, закрываем
    If IsBookOpen(sWBFullName) = False Then
        Set wb = Application.Workbooks.Open(sWBFullName)
        'изменяем значение ячейки "A1" на первом листе книги
        wb.Sheets(1).Range("A1").Value = "www.excel-vba.ru"
        ws.Close True
    End If
End Sub

При использовании функции IsBookOpen так же надо учитывать, что она может посчитать книгу открытой не только если она реально кем-то открыта, а если к ней просто нет доступа(например, заблокирован доступ со стороны администратора и т.п.).

Также см.:
Как получить данные из закрытой книги?
Как узнать существует ли лист в книге?
Как узнать существует ли модуль в книге


Статья помогла? Поделись ссылкой с друзьями!

  Плейлист   Видеоуроки


Поиск по меткам



Access
apple watch
Multex
Power Query и Power BI
VBA управление кодами
Бесплатные надстройки
Дата и время
Записки
ИП
Надстройки
Печать
Политика Конфиденциальности
Почта
Программы
Работа с приложениями
Разработка приложений
Росстат
Тренинги и вебинары
Финансовые
Форматирование
Функции Excel
акции MulTEx
ссылки
статистика

Понравилась статья? Поделить с друзьями:
  • Check grammar or no word in the dictionary
  • Check the meaning of the word in the box then complete the text
  • Check grammar in excel
  • Check the meaning of the phrases in the word list move from birth country
  • Check formulas in excel