Excelのオブジェクト解放は、簡単に描くと以下のようなコードになります。
※xlObject の部分にSheetやBookのインスタンスが入ります。
' xlObjectの解放 System.Runtime.InteropServices.Marshal.ReleaseComObject(xlObject)
ただ、Excelのオブジェクト解放にはコツがあって、これを理解していないと
タスクマネージャにExcelのプロセスが残ったままになってしまいます。
以下のサンプルソースは
Excelを新規で開く→1シート目を選択→セルに値を設定→Excelを閉じる
の操作を記述したものです。
''' <summary> ''' 解放処理サンプル ''' </summary> ''' <remarks></remarks> Private Sub sample() Dim xlApp As Application = Nothing Dim xlBooks As Workbooks = Nothing Dim xlBook As Workbook = Nothing Dim xlSheets As Sheets = Nothing Dim xlSheet As Worksheet = Nothing Dim xlRange As Range = Nothing Dim xlCells As Range = Nothing Try ' アプリケーション起動 xlApp = New Application xlApp.DisplayAlerts = False ' ワークブック作成 xlBooks = xlApp.Workbooks xlBook = xlBooks.Add ' 1シート目を指定 xlSheets = xlBook.Worksheets xlSheet = DirectCast(xlSheets(1), Worksheet) ' 対象セル抽出 xlCells = xlSheet.Cells xlRange = DirectCast(xlCells(1, 1), Range) ' セルに値を設定 xlRange.Value = "sample" ' COMオブジェクトを解放する System.Runtime.InteropServices.Marshal.ReleaseComObject(xlRange) System.Runtime.InteropServices.Marshal.ReleaseComObject(xlCells) System.Runtime.InteropServices.Marshal.ReleaseComObject(xlSheet) System.Runtime.InteropServices.Marshal.ReleaseComObject(xlSheets) System.Runtime.InteropServices.Marshal.ReleaseComObject(xlBook) System.Runtime.InteropServices.Marshal.ReleaseComObject(xlBooks) xlApp.Quit() xlApp.DisplayAlerts = True System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp) Catch ex As Exception Throw End Try End Sub
注目する点は、”sample”という文字をセルに設定するまでと、
そのあとの解放処理、それぞれの処理の順番です。
値を設定するためには、
Workbooks→Workbook→Sheets→WorkSheet→Range
と、1階層ずつ、一段ずつ階段を下りるようにセルまでを指定しなければいけません。
また解放時のオブジェクトは、生成時とは逆の順番で解放します。
このルールが守られていないと、Excelアプリケーションは終了したのに、
タスクマネージャにはExcelが残ってしまうことがあるので注意です。