How to manage excel interop objects when working with excel cells

52 Views Asked by At

I am just starting with Excel Add-in express in visual studio and have read that an expression like mySheet.Columns.countis a big "no-no" because it creates an intermediate object Columns that is not tied to any variable and cannot be later released.

With that in mind, I wrote the below code, carefully making sure that i don't chain any objects. This seems like a really time consuming way to code so wanted to sanity check my approach before progressing any further. Is there a better way?

'find ends
    Dim leftCol As Integer
    Dim tmpCell, tmpCell2 As Excel.Range
    tmpCell = Sh.Cells(1, 1) 'COM
    If (tmpCell.Value <> "") Then
        leftCol = 1
        Marshal.ReleaseComObject(tmpCell)
    Else
        tmpCell2 = tmpCell.End(XlDirection.xlToRight)
        leftCol = tmpCell2.Column
        Marshal.ReleaseComObject(tmpCell2)
        Marshal.ReleaseComObject(tmpCell)
    End If
    Marshal.ReleaseComObject(Sh)
0

There are 0 best solutions below