I was hoping someone could have a look and tidy this up for me; I have to say error handling is not strong point of mine. I have the code block below and I have been playing around with some error handles but it is not as I really want it.
What I am trying to do is ensure that if at any point there is an error the workbook and excel instance I have opened are closed down gracefully.
I am sure there are much nicer and simpler ways to achieve this than what I have come up with.
Sub QOScode()
On Error GoTo Fail
Dim app As New Excel.Application
app.Visible = False 'Visible is False by default, so this isn't necessary
Dim book As Excel.Workbook
Set book = app.Workbooks.Add(ActiveWorkbook.Path & "\QOS DGL stuff.xlsx")
'set up error handeling so if any thing happens the instance of excel with QOS sheets is closed gracefully
On Error GoTo Closebook
' MsgBox book.Sheets("ACLS").Cells(3, 3)
'Do what you have to do
'
Closebook:
On Error Resume Next
book.Close SaveChanges:=False
app.Quit
Set app = Nothing
On Error GoTo 0
Fail:
End Sub
What I want is a single On error - close app and exit sub.
Can anyone provide a sample of what would be considered best practice for doing this?
Cheers
Aaron
So this code below, when the sheet does not exist it will cause the error, why does it not skip the "book.close" statement, I know this throws an error, but I want it to ignore it?
Sub QOScode()
On Error GoTo Closebook
Dim app As New Excel.Application
app.Visible = False
Dim book As Excel.Workbook
Set book = app.Workbooks.Add(ActiveWorkbook.Path & "\QOaS DGL stuff.xlsx") 'this sheet does not exist
'
MsgBox book.Sheets("ACLS").Cells(3, 3)
'Do what you have to do
'
Closebook:
Err.Clear
On Error Resume Next
book.Close SaveChanges:=False 'Object variable or with block variable not set (error 91)
app.Quit
Set app = Nothing
On Error GoTo 0
End Sub

On Error Goto Nextwill make it go to the next statement which isapp.Quitat which point everything is as you want it to be...