Macro for closing files only if they are open

  • Thread starter Thread starter Matthew McManus
  • Start date Start date
M

Matthew McManus

Hi,

I have the following simple instruction in one of my macros.

Workbooks("fileA.xls).Activate
ActiveWorkbooks.Close

fileA.xls has been opened by an earlier macro.
Sometimes, however, the earlier macro did not need to run and s
fileA.xls will not be open and I'll get an error message.

Is there any code I can write so that the macro will close fileA.xls i
it is open, but do nothing otherwise?

Thanks
Matthe
 
You could test to see if that workbook is open:

dim tstWkbk as workbook
''' lots of code

set tstwkbk = nothing
on error resume next
set tstwkbk = workbooks("fileA.xls")
on error goto 0

if testwkbk is nothing then
'not open
else
'it's open and tstwkbk is an object variable that points at it
tstwkbk.close 'savechanges:=false 'true?
end if

========
On the other hand, you could just try to close it and ignore any possible error:

on Error Resume next
workbooks("FileA.xls").close 'savechanges:=false 'true
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top