Closing workbooks programatically

T

teepee

My problem is I want to use VBA to close 2 workbooks if they're open and do
nothing if they're not open.

Put it another way, if I put


Workbooks("book1.csv").Close SaveChanges:=False
Workbooks("book2.csv").Close SaveChanges:=False

and then book 1 and book 2 aren't already open, it creates a runtime error
which I don't want.

I thought this might work:

Dim wb As Workbook
If wb.Name = "book1.csv" Then
Workbooks("book1").Close SaveChanges:=False
'End If
'If wb.Name = "book2" Then
Workbooks("book2").Close SaveChanges:=False
'End If

But it doesn't. Anyone got any ideas?
 
T

teepee

teepee said:
My problem is I want to use VBA to close 2 workbooks if they're open and
do nothing if they're not open.

btw I found another way of doing it so that I didn't need to do this but I'd
still be interested to know if anyone knows how it might be done.
 
P

PCLIVE

Here is a short example to determine if a workbook is open. You should be
able to apply this to what you're doing.

Sub test()
On Error GoTo Skip
If Len(Application.Workbooks(Range("A1").Value).Name) > 0 _
Then
MsgBox ("workbook is open")
Exit Sub
Else
End If

Skip:
MsgBox ("workbook is not open")
End Sub


HTH,
Paul


--
 
T

Tyro

This might do what you want

Sub CloseThem()
Dim wb As Workbook
Application.ScreenUpdating = False
Application.DisplayAlerts = False
For Each wb In Application.Workbooks
If wb.Name = "book1.csv" or wb.Name = "book2.csv" Then
' wb.Save
wb.Close
End If
Next wb
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub

Tyro
 
D

Dave Peterson

Is there a reason you can't ignore the error:

On error resume next
Workbooks("book1.csv").Close SaveChanges:=False
Workbooks("book2.csv").Close SaveChanges:=False
on error goto 0

Since you're discarding any changes, it doesn't seem like this would cause a
problem.
 

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

Top