Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / productivity / Office

Dealing with Excel objects

2.71/5 (4 votes)
26 Sep 2007CPOL1 min read 1   120  
This article outlines the issue faced by most developers when it comes to dealing with Excel objects. Here, you will find code that will help in getting rid of Excel objects from the memory once they are no longer required.

Introduction

This article focuses on a small piece of code that actually simulates the EndTask function. By using this, we can force end an EXCEL.EXE process once we are done using the object.

Background

Excel objects created using MS Office Excel 2003 and below versions are basically COM objects. When we instantiate an object from code, it creates an EXCEL.EXE process in the system processes. This corresponds to a single instance of Excel. The .NET CLR is not responsible for releasing COM objects. All it can do is reduce the reference count of COM objects, which would then be cleared off by the GC, which is again not under the control of the developer as the GC could run at any instant. So there is no means of releasing an Excel object from the memory immediately. Once there are many EXCEL.EXE appearing in the Task Manager, it may end up in lack of memory errors.

Using the code

We would use the EndTask method of user32.dll to simulate the end task functionality which will release the EXCEL.EXE from the memory (Task Manager).

You need to import the EndTask method as shown below:

VB
//method import
Private Declare Function EndTask Lib "user32.dll" Alias _
                "EndTask" (ByVal hwnd As Long) As Long
    //Getting the window handle for the excel
    If (objExcel.Version) < "10.0" Then
        iHandle = FindWindow(Nothing, ObjExcel.Caption)
    Else
        iHandle = objExcel.Parent.Hwnd
    End If

    //Calling the EndTask Method
    intResult = EndTask(iHandle)

Points of Interest

You would not require any special permissions to access the EndTask method. So if you can create the Excel object, you can very easily destroy it using this piece of code.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)