| 分類:[VB.NET (Windows)]
こんばんは、ボビンと申します。
いつもサイトを開発の参考にさせていただいています。 そこで疑問があり、ご質問させていただきました。よろしくお願いします。
サンプルにある、「COM オブジェクトの参照カウントを解放する」のVB.NETですが、
このように書くのは間違いでしょうか?
↓↓↓
' COM オブジェクトの参照カウントを解放する
' VB.NET ' 必要な変数は Try の外で宣言する Dim xlApplication As Excel.Application
' COM オブジェクトの解放を保証するために Try 〜 Finally を使用する Try xlApplication = New Excel.Application()
' 警告メッセージなどを表示しないようにする xlApplication.DisplayAlerts = False
Dim xlBooks As Excel.Workbooks = xlApplication.Workbooks Dim xlBook As Excel.Workbook = xlBooks.Add() Dim xlSheets As Excel.Sheets = xlBook.Worksheets Dim xlSheet As Excel.Worksheet = DirectCast(xlSheets(1), Excel.Worksheet) Dim xlCells As Excel.Range = xlSheet.Cells Dim xlRange As Excel.Range = DirectCast(xlCells(6, 4), Excel.Range)
Try ' Microsoft Excel を表示する xlApplication.Visible = True
' 1000 ミリ秒 (1秒) 待機する System.Threading.Thread.Sleep(1000)
' Row=6, Column=4 の位置に文字をセットする xlRange.Value2 = "あと 1 秒で終了します"
' 1000 ミリ秒 (1秒) 待機する System.Threading.Thread.Sleep(1000)
Finally If Not xlRange Is Nothing Then System.Runtime.InteropServices.Marshal.ReleaseComObject(xlRange) End If If Not xlCells Is Nothing Then System.Runtime.InteropServices.Marshal.ReleaseComObject(xlCells) End If If Not xlSheet Is Nothing Then System.Runtime.InteropServices.Marshal.ReleaseComObject(xlSheet) End If If Not xlSheets Is Nothing Then System.Runtime.InteropServices.Marshal.ReleaseComObject(xlSheets) End If
If Not xlBook Is Nothing Then Try xlBook.Close() Finally System.Runtime.InteropServices.Marshal.ReleaseComObject(xlBook) End Try End If If Not xlBooks Is Nothing Then System.Runtime.InteropServices.Marshal.ReleaseComObject(xlBooks) End If End Try Finally
If Not xlApplication Is Nothing Then Try xlApplication.Quit() Finally System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApplication) End Try End If End Try
↑↑↑
Try〜Finallyがたくさんあるところを、まとめただけですが、 試してみたところ サンプルも、こちらのコードもタスクマネージャのプロセスから"EXCEL.EXE"は消えました。 こちらの書き方では、問題がありますでしょうか。 サンプルの書き方でないと、やはり正しく解放されないのでしょうか? それとも、わかりやすくするために、Try〜Finallyがたくさんある、サンプルの書き方となっているのでしょうか?
ズレた質問だったらすみませんが、よろしくお願いします。 環境はwin2K + VB2005 + office2003 です。
|