Closing random opened workbook.

Koranga

New Member
Joined
Mar 30, 2017
Messages
7
Hello All,

I have some workbooks open (manually), now I am trying to close 1 of them using VBA function Workbooks.Close().
Somewhere I found a way of doing it
Workbooks("FileName").Close
but somehow for me its not working and throwing error which says "Subscript out of Range".

The code that I am using is:
Sub Closing()


Dim DestFile As String
Dim wb As Workbook
DestFile = Application.GetOpenFilename()


ret = Isworkbookopen(DestFile)
If ret = False Then
'open file
Set wb = Workbooks.Open(DestFile)
Else
'Close the file
Workbooks(DestFile).Close SaveChanges:=True 'Here I am getting Subscript of of Range Error
End If
End Sub

Here I am selecting a file to open and if the file is already open then instead of opening I am closing the opened file.
The object for the workbooks are not available as they were opened manually, so I am not able to close a specific workbook.
Could anyone please let me know is there any other way for doing the same(closing the file) or am I missing something.
Thanks in advance.
 

Excel Facts

Add Bullets to Range
Select range. Press Ctrl+1. On Number tab, choose Custom. Type Alt+7 then space then @ sign (using 7 on numeric keypad)
Firstly, I am not a pro. But it may be because you have not declared your variable "ret".

Dim ret as Boolean
 
Last edited:
Upvote 0
This will remove the file path from DestFile and leave just the file name.

Code:
        [COLOR=green]'Close the file[/COLOR]
        Filename = Mid(DestFile, InStrRev(DestFile, "\") + 1)
        Workbooks(Filename).Close SaveChanges:=[COLOR=darkblue]True[/COLOR]
 
Last edited:
Upvote 0

Forum statistics

Threads
1,215,515
Messages
6,125,277
Members
449,220
Latest member
Excel Master

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