I feel your comments warrant me posting this as an answer so that I may be a bit more thorough. This is meant only to add to the answer provided by mielk!
The object hierarchy in excel is roughly summarized by "An Excel Application owns workbooks. An Excel Workbook owns Worksheets. An Excel Worksheet owns Ranges." For more info on that look here.
When you click on an excel file to open it you are effectively doing 2 things:
- Starting up an Excel "Application"
- Opening up a Workbook that that "Application" will "own"
When you open up subsequent Excel files, Excel will skip step one and simply open a workbook in the Excel Application that is already running. Note this means that similar to how a Workbook can have many Worksheets a single Excel Application can have multiple Workbooks that belong to it.
There are multiple ways to access these workbooks in VBA. One way is to use the application's Workbooks
member much like you used a Workbook
's Sheets
member to access worksheets. Often though you simply want to access the Workbook that the user is currently editing/working on. To do this you can use ActiveWorkbook
which is automatically updated for you whenever the user begins work on a different workbook.
Another Workbook you will often want to use is the workbook that "houses" the code you are running. You can do this by using ThisWorkbook
. If you open up the VBA editor and look at the project viewer, you can even see a reference to ThisWorkbook
! If you want your code to only update/alter the workbook that contains it then ThisWorkbook
is the way to go.
As an example:
Let's say you have a macro to loop through all of the open workbooks and put the number of sheets each Workbook "owns" into some Worksheet in the "master" workbook.
You could do something like this:
Sub CountThem()
Dim wb As Workbook
Dim outputCell As Range
Dim nextRow As Integer
nextRow = 1
For Each wb In Application.Workbooks
wb.Activate
ThisWorkbook.Sheets("MySheet").Cells(nextRow, 1).Value = ActiveWorkbook.Sheets.Count
nextRow = nextRow + 1
Next
End Sub
You would put this code as a module in the "Master" workbook.
Let me know if this clears things up for you! :)