Error handler close workbook if opened during code

rhombus4

Well-known Member
Joined
May 26, 2010
Messages
586
Office Version
  1. 365
  2. 2016
Platform
  1. Windows
During my code if there is an error it jumps to errorhandler which will close a workbook if it was opened during the code. If it wasn't opened it can just ignore it
However I get run time error 9 subscript out of range on the set wb line in eh:

VBA Code:
Sub test()
On error goto eh
Code

Dim wb as workbook
Set wb = workbooks.open("c:\test.xlsx")

Some more code

Exit sub

eh:
On error resume next
Set wb = workbooks("test.xlsx")
wb.close
On error goto 0

End sub
 
Sorry one quick question Currently if no errors
I have

VBA Code:
On error resume next
 wb.close savechanges: = True
On error goto 0

Is it better to use your code and add save changes

VBA Code:
If Not wb Is Nothing Then wb.Close savechanges: = True
 
Upvote 0

Excel Facts

How to create a cell-sized chart?
Tiny charts, called Sparklines, were added to Excel 2010. Look for Sparklines on the Insert tab.
I would check to see if the workbook exists rather then using the on error, but that's more personal preference.
 
Upvote 0
Check workbook exists??

Is that what your code checks for
 
Upvote 0
I didn't phrase that very well, it checks to see if wb has been set
 
Upvote 0
AHH ok. so your code to check if workbook has been set and adding savechanges: = true can be used instead of

On error resume next
wb.close savechanges: = True
On error goto 0
 
Upvote 0

Forum statistics

Threads
1,213,494
Messages
6,113,986
Members
448,538
Latest member
alex78

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