VBA to close mulitiple files

rsulliva

Board Regular
Joined
Sep 13, 2007
Messages
133
Office Version
  1. 365
Platform
  1. Windows
I would like a VBA script that can close multiple files. There can be up to 50 files open at one time with the name of "Metrics Table (2) (*)", where the * is any number between 1 and 1000. Example "Metrics Table (2) (16)". Data is pulled from these files and then the file is no longer needed (it actually could and will be manually deleted) but at least I need these files to close when the macro is run. The file in which the macro is run is the master file and will NOT be closed.

Here is a code I found that I imagine could be modified to use a wildcard somehow.

VBA Code:
Sub CloseWorkbook()
Workbooks("Metrics Table (2) (16).xlsx").Close SaveChanges:=False

I tried to use this one, but there could be other workbooks open that I don't want to close

VBA Code:
Sub CloseAllWbksExceptCurrent()    
Dim wb As Workbook    
For Each wb In Workbooks        
If wb.Name <> ThisWorkbook.Name Then          
wb.Close SaveChanges:=False        
End If    
Next wb
End Sub

Thanks for any help.
 

Excel Facts

Why are there 1,048,576 rows in Excel?
The Excel team increased the size of the grid in 2007. There are 2^20 rows and 2^14 columns for a total of 17 billion cells.
Try this:

VBA Code:
Sub CloseAllWbksExceptCurrent()
  Dim wb As Workbook
  For Each wb In Workbooks
    If wb.Name <> ThisWorkbook.Name Then
      If InStr(1, wb.Name, "Metrics Table (2) (", vbTextCompare) > 0 Then
        wb.Close SaveChanges:=False
      End If
    End If
  Next wb
End Sub
 
Upvote 0

Forum statistics

Threads
1,224,507
Messages
6,179,181
Members
452,893
Latest member
denay

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