Excel vba for all open workbooks

VBA List all Open Workbooks in Excel. It helps to know all open workbooks name. It is easy to handle and shift between workbooks. We have an option to open multiple workbooks in MS Office Excel. Let us see in the following tutorial how to list open Workbooks in Excel VBA.

Here is the following syntax to List all Open Workbooks in Excel VBA.

For Each Workbook in Application.Workbooks
      Statements...
Next

Where Workbook: It represents Workbook object which is part of workbooks collection.

VBA Code to List all Workbooks in Excel VBA

Let us see the following example macro to List all Open Workbooks in Excel VBA

'VBA List Open Workbooks in Excel
Sub VBA_List_All_Open_Workbooks()
    
    'Variable declaration
    Dim xWorkbook As Workbook
    Dim sWorkbookName As String
    Dim iCount As Integer
    
    'Intialise value to a variable
    iCount = 2
    
    Sheets("WB_Names").Range("A1") = "Names of Available Workbooks"
    
    'Loop through all workbooks
    For Each xWorkbook In Application.Workbooks
        Sheets("WB_Names").Range("A" & iCount) = xWorkbook.Name & vbCrLf
        
        'Increase value
        iCount = iCount + 1
    Next

End Sub

Instructions to Run VBA Macro Code or Procedure:

You can refer the following link for the step by step instructions.

Instructions to run VBA Macro Code

Other Useful Resources:

Click on the following links of the useful resources. These helps to learn and gain more knowledge.

VBA Tutorial VBA Functions List VBA Arrays in Excel Blog

VBA Editor Keyboard Shortcut Keys List VBA Interview Questions & Answers

Author: Oscar Cronquist Article last updated on March 19, 2019

In this post, I am going to demonstrate how to automatically create a new sheet in the current workbook and list all open workbooks and their sheets using a VBA macro.

The image above shows the new worksheet, it contains the names of the workbooks and corresponding worksheets I have currently open.

Macro code

'Name macro
Sub ListWorkbooks()

'Declare variables and data types
Dim wb As Workbook
Dim ws As Worksheet
Dim i As Single, j As Single

'Create a new worksheet and save to object ws
Set ws = Sheets.Add

'Go through open workbooks
For j = 1 To Workbooks.Count

    'Save workbook name to cell A1 and downwards
    Range("A1").Cells(j, 1) = Workbooks(j).Name
    
    'Iterate through worksheets in given workbook
    For i = 1 To Workbooks(j).Sheets.Count
  
            'Save worksheet names to cell B1 and cells further right
            Range("A1").Cells(j, i + 1) = Workbooks(j).Sheets(i).Name

    'Continue with next worksheet
    Next i

'Continue with next workbook
Next j
End Sub

How to copy the macro to your workbook

  1. Press Alt+F11 to open the VB Editor.
  2. Press with right mouse button on on your workbook in the Project Explorer.
  3. Press with left mouse button on «Insert» and then «Module».
  4. Copy macro code.
  5. Press with left mouse button on in code module window to see the input prompt.
  6. Paste code to code module.
  7. Return to Excel.

How to run the macro

  1. Go to «Developer» tab on the ribbon.
  2. Press with left mouse button on «Macros» button.
  3. Select «ListWorkbooks» macro.
  4. Press with left mouse button on «Run» button.

test

test

test

test

test

Apply drop-down lists dynamically
This article demonstrates how to automatically create drop-down lists if adjacent data grows, there are two methods explained here. The […]

test

Auto resize columns as you type
Excel does not resize columns as you type by default as the image above demonstrates. You can easily resize all […]

test

Automate data entry [VBA]
This article demonstrates how to automatically enter data in cells if an adjacent cell is populated using VBA code. In […]

test

Basic data entry [VBA]
In this small tutorial, I am going to show you how to create basic data entry with a small amount […]

test

Calendar with scheduling [vba]
Here is my contribution to all excel calendars out there. My calendar is created in Excel 2007 and uses both […]

test

test

test

test

Consolidate sheets [vba]
Question: I have multiple worksheets in a workbook. Each worksheets is project specific. Each worksheet contains almost identical format. The […]

test

Copy a dynamic cell range [VBA]
In this blog post, I will demonstrate some VBA copying techniques that may be useful if you don’t know the […]

test

test

test

test

test

Create a Print button [VBA]
This article describes how to create a button and place it on an Excel worksheet then assign a macro to […]

test

test

test

test

test

Edit invoice data [VBA]
In a previos post:Excel vba: Save invoice data we added/copied data between sheets. This post describes how to overwrite existing […]

test

Excel calendar [VBA]
This workbook contains two worksheets, one worksheet shows a calendar and the other worksheet is used to store events. The […]

test

test

test

test

test

test

test

Hide specific columns programmatically
This article describes a macro that hides specific columns automatically based on values in two given cells. I am also […]

test

Hide specific worksheets programmatically
This article demonstrates techniques to hide and unhide worksheets programmatically. The image above shows the Excel window and the worksheet […]

test

test

test

test

test

test

test

test

test

test

test

test

How to quickly select blank cells
In this smaller example, column D (Category) has empty cells, shown in the picture above. If your column contains thousands of […]

test

test

test

How to use DIALOG BOXES
A dialog box is an excellent alternative to a userform, they are built-in to VBA and can save you time […]

test

How to use the Scroll Bar
This article demonstrates how to insert and use a scroll bar (Form Control) in Excel. It allows the user to […]

test

Identify missing numbers in a column
The image above shows an array formula in cell D6 that extracts missing numbers i cell range B3:B7, the lower […]

test

test

Locate a shape in a workbook
This article demonstrates how to locate a shape in Excel programmatically based on the value stored in the shape. The […]

test

Move a shape [VBA]
This article demonstrates how to move a shape, a black arrow in this case, however, you can use whatever shape […]

test

test

Normalize data [VBA]
To be able to use a Pivot Table the source data you have must be arranged in way that a […]

test

Open Excel files in a folder [VBA]
This tutorial shows you how to list excel files in a specific folder and create adjacent checkboxes, using VBA. The […]

test

test

test

test

test

test

test

test

test

Save invoice data [VBA]
This article demonstrates a macro that copies values between sheets. I am using the invoice template workbook. This macro copies […]

test

Search two related tables [VBA]
This article demonstrates a macro that automatically applies a filter to an Excel defined Table based on the result from […]

test

Select and view invoice [VBA]
This post demonstrates how to view saved invoices based on the invoice number using a userform. The userform appears when the […]

test

test

test

test

test

test

Toggle a macro on/off using a button
This article demonstrates how the user can run a macro by press with left mouse button oning on a button, […]

test

test

Working with COMBO BOXES [Form Controls]
This blog post demonstrates how to create, populate and change comboboxes (form control) programmatically. Form controls are not as flexible […]

test

Working with FILES
In this blog article, I will demonstrate basic file copying techniques using VBA (Visual Basic for Applications). I will also […]

test

Working with TEXT BOXES [Form Controls]
There are two different kinds of text boxes, Form controls and ActiveX Controls. Form controls can only be used on […]

Latest updated articles.

More than 300 Excel functions with detailed information including syntax, arguments, return values, and examples for most of the functions used in Excel formulas.

More than 1300 formulas organized in subcategories.

Excel Tables simplifies your work with data, adding or removing data, filtering, totals, sorting, enhance readability using cell formatting, cell references, formulas, and more.

Allows you to filter data based on selected value , a given text, or other criteria. It also lets you filter existing data or move filtered values to a new location.

Lets you control what a user can type into a cell. It allows you to specifiy conditions and show a custom message if entered data is not valid.

Lets the user work more efficiently by showing a list that the user can select a value from. This lets you control what is shown in the list and is faster than typing into a cell.

Lets you name one or more cells, this makes it easier to find cells using the Name box, read and understand formulas containing names instead of cell references.

The Excel Solver is a free add-in that uses objective cells, constraints based on formulas on a worksheet to perform what-if analysis and other decision problems like permutations and combinations.

An Excel feature that lets you visualize data in a graph.

Format cells or cell values based a condition or criteria, there a multiple built-in Conditional Formatting tools you can use or use a custom-made conditional formatting formula.

Lets you quickly summarize vast amounts of data in a very user-friendly way. This powerful Excel feature lets you then analyze, organize and categorize important data efficiently.

VBA stands for Visual Basic for Applications and is a computer programming language developed by Microsoft, it allows you to automate time-consuming tasks and create custom functions.

A program or subroutine built in VBA that anyone can create. Use the macro-recorder to quickly create your own VBA macros.

UDF stands for User Defined Functions and is custom built functions anyone can create.

A list of all published articles.

In this Article

  • The Workbook Object
    • Workbook Index Number
  • Activate Workbook, ActiveWorkbook, and ThisWorkbook
    • Activate Workbook
    • ActiveWorkbook
    • ThisWorkbook
  • Open Workbook
    • Open and Assign to Variable
    • Open File Dialog
  • Create New (Add) Workbook
    • Add New Workbook to Variable
  • Close Workbook
    • Close & Save
    • Close without Save
  • Workbook Save As
  • Other Workbook VBA Examples
    • Workbook Name
    • Protect Workbook
    • Loop Through all Open Workbooks
    • Workbook Activate Event

This guide will introduce you working with the Workbook Object in VBA.

The Workbook Object

First, in order to interact with workbooks in VBA, you must understand the Workbook Object.

With the workbook object, you can reference workbooks by their name like this:

Workbooks("Book2.xlsm").Activate

However, this code will only work if the workbook is open. If the workbook is closed, you will need to provide the full workbook path:

Workbooks.Open ("C:UsersStevePC2Downloadsbook2.xlsm")

Instead of typing out the full path, if your desired workbook is in the same directory as the workbook where your code is stored, you could use this line code to open the workbook:

Workbooks.Open (ThisWorkbook.Path & "book2.xlsm")

This makes use of the ThisWorkbook object that we will discuss in the next section.

Workbook Index Number

Last, you can reference workbooks by their “Index Number”. The index number of a workbook corresponds to the order that the workbook was opened (technically its the workbook’s position in the Workbooks Collection).

Workbooks(1).Activate

This is useful if you want to do something like close the first (or last) opened workbook.

Activate Workbook, ActiveWorkbook, and ThisWorkbook

If a workbook is NOT ACTIVE, you can access the Workbook’s objects like this:

Workbooks("Book2.xlsm").Sheets("Sheet1").Range("A1").value = 1

However, if the workbook is Active, you can omit the workbook object:

Sheets("Sheet1").Range("A1").value = 1

And if you want to interact with the workbook’s active sheet, you can also ommit the sheets object:

Range("A1").value = 1

Activate Workbook

To activate a workbook, use the Activate Method.

Workbooks("Book2.xlsm").Activate

Now you can interact with Book2’s object’s without explicitly stating the workbook name.

ActiveWorkbook

The ActiveWorkbook object always refer to the active workbook. This is useful if you’d like to assign the ActiveWorkbook to a variable to use later.

Dim wb As Workbook
Set wb = ActiveWorkbook

ThisWorkbook

The ThisWorkbook object always refers to the workbook where the running code is stored. To activate ThisWorkbook, use this line of code:

ThisWorkbook.Activate

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

automacro

Learn More

Open Workbook

To open a workbook, use the Open Method:

Workbooks.Open ("C:UsersStevePC2Downloadsbook2.xlsm")

The newly opened workbook will always become the ActiveWorkbook, allowing you to easily interact with it.

ActiveWorkbook.Save

The Open Method has several other arguments, allowing you to open read-only, open a password-protected workbook, and more. It’s covered here in our article about Opening / Closing Workbooks.

Open and Assign to Variable

You can also open a workbook and assign it to a variable at the same time:

Dim wb As Workbook
Set wb = Workbooks.Open("C:UsersStevePC2Downloadsbook2.xlsm")

Open File Dialog

You can also trigger the Open File Dialog Box like this:

Sub OpenWorkbook ()
 
    Dim strFile As String
 
    strFile = Application.GetOpenFilename()
    Workbooks.Open (strFile)
 
End Sub

vba open close file

VBA Programming | Code Generator does work for you!

Create New (Add) Workbook

This line of code will create a new workbook:

Workbooks.Add

The new workbook now becomes the ActiveWorkbook, allowing you to interact with it (ex. save the new workbook).

Add New Workbook to Variable

You can also add a new workbook directly to a variable:

Dim wb As Workbook
Set wb = Workbooks.Add

Close Workbook

Close & Save

To close a workbook with saving, use the Close Method with SaveChanges set to TRUE:

ActiveWorkbook.Close SaveChanges:=True

Close without Save

To close without saving, set SaveChanges equal to FALSE:

ActiveWorkbook.Close SaveChanges:=False

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

Workbook Save As

The SaveAs Method is used to save a workbook as.

To save a workbook with a new name, in the same directory, you can imply use this:

ActiveWorkbook.SaveAs "new"

where “new” is the new file name.

To save a workbook in a new directory with a specific file extension, simply specify the new directory and file name:

ActiveWorkbook.SaveAs "C:UsersStevePC2Downloadsnew.xlsm"

Other Workbook VBA Examples

Workbook Name

To get the name of a workbook:

MsgBox ActiveWorkbook.Name

Protect Workbook

To protect the workbook structure from editing, you can use the Protect Method (password optional):

Workbooks("book1.xlsm").Protect "password"

To unprotect a workbook use the UnProtect Method:

Workbooks("book1.xlsm").Unprotect "password"

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

Loop Through all Open Workbooks

To loop through all open workbooks:

Sub LoopThroughWBs()
    
    Dim wb As Workbook
    
    For Each wb In Workbooks
        MsgBox wb.Name
    Next wb

End Sub

Workbook Activate Event

You can run some code whenever a specific workbook is opened with the Workbook Open Event.

Place this procedure your workbook’s ThisWorkbook Module:

Private Sub Workbook_Open()
    Sheets("sheet1").Activate
End Sub

This procedure will activate Sheet1 every time the workbook is opened.

What This VBA Code Does

This bit of VBA code shows you how to loop through all currently open Excel workbooks and make a modification to them.  In the example code below today’s date is added to the first worksheet in Cell A1.  Notice also that the loop will skip a Personal Macro workbook if one is created.

Using VBA Code Found On The Internet

Now that you’ve found some VBA code that could potentially solve your Excel automation problem, what do you do with it? If you don’t necessarily want to learn how to code VBA and are just looking for the fastest way to implement this code into your spreadsheet, I wrote an article (with video) that explains how to get the VBA code you’ve found running on your spreadsheet.

Getting Started Automating Excel

Are you new to VBA and not sure where to begin? Check out my quickstart guide to learning VBA. This article won’t overwhelm you with fancy coding jargon, as it provides you with a simplistic and straightforward approach to the basic things I wish I knew when trying to teach myself how to automate tasks in Excel with VBA Macros.

Also, if you haven’t checked out Excel’s latest automation feature called Power Query, I have put together a beginner’s guide for automating with Excel’s Power Query feature as well! This little-known built-in Excel feature allows you to merge and clean data automatically with little to no coding!

How Do I Modify This To Fit My Specific Needs?

Chances are this post did not give you the exact answer you were looking for. We all have different situations and it’s impossible to account for every particular need one might have. That’s why I want to share with you: My Guide to Getting the Solution to your Problems FAST! In this article, I explain the best strategies I have come up with over the years to get quick answers to complex problems in Excel, PowerPoint, VBA, you name it

I highly recommend that you check this guide out before asking me or anyone else in the comments section to solve your specific problem. I can guarantee that 9 times out of 10, one of my strategies will get you the answer(s) you are needing faster than it will take me to get back to you with a possible solution. I try my best to help everyone out, but sometimes I don’t have time to fit everyone’s questions in (there never seem to be quite enough hours in the day!).

I wish you the best of luck and I hope this tutorial gets you heading in the right direction!

Chris
Founder, TheSpreadsheetGuru.com

VBA Code To Access All Open Excel Files

The code below will loop through all workbooks that are open in current system.

If you want to scan through all the opened Excel files, assign it to a Workbook object and read or write to them, then this code will be much useful.

Collection Used: Application.workbooks

Excel Macro to Search All Opened Workbooks

Copy paste this code to your VBA project, to search or verify any opened files with Excel Application (CSV, XLSM, XLSX etc., )

Sub Loop_Thru_All_Open_Workbooks_Excel_Files()
    'Define a Workbook Object
    Dim oWb As Workbook
    
    'Traverse through each workbook Opened - Using Excel Application Object
    For Each oWb In Application.Workbooks
        'Check for File name
        If oWb.Name <> "FileName.xlsx" Then
            'Check for File Content
            If oWb.Sheets(1).Cells(1, 1) = "Text To Compare" Then
                MsgBox "File Searching for Found"
            End If
        End If
        
        'Read Next Opened Excel File
    Next oWb
End Sub

Once the file that you are searching for is found, then using the Workbook object, any file operations like read/write can be performed.

VBA Get Name & Path Of All Open Workbooks

Here is another very useful implementation of this code.

This will create an index of all open Excel files into current active sheet along with its folder path.

Sub Get_Names_Of_All_Open_Workbook()
    'Define a Workbook Object
    Dim oWb As Workbook, iSh As Worksheet, iRow As Double
    Set iSh = ThisWorkbook.Sheets(1)
    
    'Traverse through each workbook Opened - Using Excel Application Object
    iRow = 1
    For Each oWb In Application.Workbooks
        'Get File Name, Path & any other Property
        iSh.Cells(iRow, 1) = oWb.Name
        iSh.Cells(iRow, 2) = oWb.Path
        iSh.Cells(iRow, 3) = oWb.Creator
        iRow = iRow + 1
    Next oWb
End Sub

If you have opened a large number of Excel files & get a list of all its names, then this code will generate the list.

Понравилась статья? Поделить с друзьями:
  • Excel vba font not bold
  • Excel vba font color in cell
  • Excel vba finding empty cell
  • Excel vba find не работает
  • Excel vba find найти все