Looping through open workbooks

aziz rasul

Active member
Local time
Today, 17:57
Joined
Jun 26, 2000
Messages
1,935
When I loop through the 2 open workbooks using vba it only recognizes one?

Code:
Dim xlWB As Excel.Workbook
Dim objExcelApp As Excel.Application

Set objExcelApp = GetObject(, "Excel.Application")

For Each xlWB In objExcelApp.Workbooks
    Debug.Print xlWB.Name
Next xlWB

Set objExcelApp = Nothing
Set xlWB = Nothing

One of the workbooks is a xlsm file and the other is a xlsx file. It doesn't recognize the xlsx file. Tried opening a separate xlsx file and it recognizes that.

If I have only the rogue xlsx open on it's own, then the code recognizes it!

I essentially want to work on 2 Excel files in my code.
 
the code may only see the default wb ,since you never opened one you use.
your instance MUST open the files. (not have them previously open from a different instance access does not control)

Code:
with objExcelApp
   .Workbooks.Open "c:\folder\myfile.xlsx"
   .Workbooks.Open "c:\folder\different file.xlsm"
   for each wb in .Workbooks
       'do stuff 
   next
end with
 
Many thanks for that. That worked.
 

Users who are viewing this thread

Back
Top Bottom