Irfan Arif
Irfan Arif

Reputation: 25

Excel.Range object not disposing so not Closing the Excel process

I am banging my head since hours to dispose the Excel.Range Object creating by the statement below. I Have checked almost all the Discussions regarding it on Stack Overflow.

oSheet.Range("A1", "H1").Merge()

When i comment out this line Excel Application closes successfully. But when i use this line it creates the Excel.Range object which is not disposing of by GC. Can anyone please help me out.

Thanks

Upvotes: 2

Views: 544

Answers (1)

Hans Olsson
Hans Olsson

Reputation: 55009

You shouldn't do nested calls like that, instead change it to be something like:

Dim r As Object = oSheet.Range("A1", "H1")
r.Merge()

Then r can be disposed properly by a:

Marshal.ReleaseComObject(r)

And then you can reuse the variable if you want:

r = oSheet.Cells(TitleRow3, 1)
' do something with r
Marshal.ReleaseComObject(r)
r = 'get a new range from somewhere
' do something with r
Marshal.ReleaseComObject(r)
...

Upvotes: 1

Related Questions