VBA: Test if Workbook is Open, by Workbook Name

January 12th, 2005 | Categories: Worksheets | Tags:

Here is some real basic code for testing if a workbook is currently open by testing for a workbook’s name, not the fully qualified name including the path.

I was writing code in a spreadsheet that altered sheets in another workbook, and wanted to make sure workbook 2 was open before the code executed in workbook 1.

Sub TestByWorkbookName()
Dim wb As Workbook

For Each wb In Workbooks

'replace between the quotes with workbook to test for
If wb.Name = "New Microsoft Excel Worksheet.xls" Then

MsgBox "Found it"
Exit Sub 'call code here, we'll just exit for now

End If

Next

End Sub
  1. January 12th, 2005 at 01:27
    Reply | Quote | #1

    Hi.

    The code which I use and the most common on newsgroups is as follows:

    Sub test()
    Dim wkb As Workbook

    On Error Resume Next
    Set wkb = Workbooks(“New Microsoft Excel Worksheet.xls”)
    On Error GoTo 0

    If Not wkb Is Nothing Then MsgBox “Found it”
    End Sub

    Cheers,
    Rob

  2. Mark
    January 12th, 2005 at 01:48
    Reply | Quote | #2

    Thanks Rob, that does look better.

    BTW, Nice site! The 3D model rotate tool is amazing, I’ll link it later today.

  3. mik
    February 3rd, 2009 at 17:36
    Reply | Quote | #3

    I’d rather use the code listed first (TestByWorkbookName), but it didn’t work for me.

    You didn’t set wb, how will it know what to compare the name to?

    How do I set wb to know all currently open workbooks?