Close workbook with variable

Ingemar

New Member
Joined
May 8, 2017
Messages
23
Office Version
  1. 365
Platform
  1. Windows
Hello!

I open an Excel file with the VBA code below using a variable called "Filename".

' File filters
Filter = "Excel Workbook (*.xlsx,*xlsx,Excel Makro-enabled Workbook (*.xlsm),*.xlsm,Excel 97-2003 Workbook (*.xls),*.xls,"

' Set Dialog Caption
Title = "Select a File to Open"

With Application
' Set File Name to selected File
Filename = .GetOpenFilename(Filter, FilterIndex, Title)
End With

' Exit on Cancel
If Filename = False Then
MsgBox "No file was selected."
Exit Sub
End If

' Open File
Workbooks.Open Filename

How can I close the file opened with the variable "Filename"? I have tried something like below without success.

Workbooks(Filename).Close Savechanges:=False

Grateful for any help

Kind regards
 

Excel Facts

How to find 2nd largest value in a column?
MAX finds the largest value. =LARGE(A:A,2) will find the second largest. =SMALL(A:A,3) will find the third smallest
You can replace this:

VBA Code:
     Open File
    Workbooks.Open Filename

With this:

VBA Code:
    Dim WB As Workbook
    ' Open File
    Set WB = Workbooks.Open(Filename:=Filename)
    
    WB.Close SaveChanges:=False

Also you should try to pick variable names that are not the same as VBA keywords or parameter names. It will save you much grief in the long run. In other words
Workbooks.Open(Filename:=MyFilename) is better than Workbooks.Open(Filename:=Filename)
 
Upvote 0
Solution
Hello rlv01!

Your code works great including your remarks about VBA keywords. Thank you very much.

Kind regards

Ingemar
 
Upvote 0

Forum statistics

Threads
1,223,888
Messages
6,175,213
Members
452,618
Latest member
Tam84

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