VBA: For Each wb In Workbooks - doesn't work

thedogg

Board Regular
Joined
Sep 22, 2015
Messages
154
I have a problem with "For Each wb In Workbooks". I want to close all workbooks which haven't met certain condition.

Code:
Dim wb As Workbook
For Each wb In Workbooks
wb.Activate
    If Left(wb.Sheets(1).name, 4) <> "BOM." Then
        wb.Close SaveChanges:=False
    ElseIf Left(wb.Sheets(1).name, 4) = "BOM." And wb.Sheets(1).Tab.Color = 49407 Or wb.Sheets(1).Tab.Color = 49407 Or wb.Sheets(1).Tab.Color = 5296274 Then
    wb.Close SaveChanges:=False
    End If
Next


Macro randomly close what should be closed. Sometimes it depends which workbook is as Workbook(1). Could you advise?
 
the code is closing the workbook and stop working after that. The code is not going further to next workbook in case of check.

The code is not in any of macro workbook. The code is in .xlam
 
Last edited:
Upvote 0

Excel Facts

Show numbers in thousands?
Use a custom number format of #,##0,K. Each comma after the final 0 will divide the displayed number by another thousand
An xlam is a workbook. It will be included in the loop.
 
Upvote 0
In post number 2 i said put brackets around your or conditions. It doesnt appear you did that. Then in post number 3 i said you need to avoid closing the workbook where the macro was housed. It doesnt appear you did that either. Why would that be?
 
Upvote 0

Forum statistics

Threads
1,224,823
Messages
6,181,184
Members
453,020
Latest member
Mohamed Magdi Tawfiq Emam

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top