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

Quick Sum
Select a range of cells. The total appears in bottom right of Excel screen. Right-click total to add Max, Min, Count, Average.
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,215,069
Messages
6,122,959
Members
449,096
Latest member
Anshu121

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