3

I have the following object that later in my code I want to dispose() IF it exists. Is there a way to find if it exists?

Public objExcel As Excel.Application

The best I could come up with is to put the disposal into a try...catch block like this:

Try
   objExcel.dispose()
Catch ex As Exception
   'do nothing
End Try

Does anyone have a more elegant, less kludgy method?

ElektroStudios
  • 19,105
  • 33
  • 200
  • 417
ScotterMonkey
  • 1,007
  • 12
  • 25

2 Answers2

2

To dispose of an Excel object completely you must you the marshal class. System.Runtime.InteropServices.Marshal. You also need to release all the excel objects in reverse order - Worksheet, workbook, excel object. If you don't you can see the Excel process in task manager.

System.Runtime.InteropServices.Marshal.FinalReleaseComObject(obgExcel)
OneFineDay
  • 9,004
  • 3
  • 26
  • 37
1

First check if object is initialized, then you can safely dispose it.

If objExcel isnot nothing then objExcel.dispose()
ElektroStudios
  • 19,105
  • 33
  • 200
  • 417
  • This will cause problems and throw ObjectDisposed Exceptions. You would need to use objExcel = Nothing after you have disposed of it, before checking with IsNot Nothing. – henda79 Oct 29 '15 at 17:33