Excel出力の解放について質問です。
下記URLを参考に作成しましたが、出力をし終えたときにプロセスを見るとExcelの解放がされません。
http://hanatyan.sakura.ne.jp/dotnet/Excel01.htm
助言をもらえないでしょうか?
With SaveFileDialog1
.FileName = savefilename
If .ShowDialog() = Windows.Forms.DialogResult.OK Then
wstrPath = .FileName()
If Func_Excelチェック(wstrPath) = False Then
Exit Function
End If
End If
End With
Dim excel As New Excel.Application
Dim xlbooks As Excel.Workbooks = excel.Workbooks
Dim xlbook As Excel.Workbook = xlbooks.Add
Dim xlsheets As Excel.Sheets = xlbook.Worksheets
Dim xlsheet As Excel.Worksheet = xlsheets.Item(1)
Dim xlCells As Excel.Range
Dim xlRange1 As Excel.Range
xlCells = xlsheet.Cells
Dim i As Integer = 1
作成データテーブルに接続
xlRange1 = xlCells(1, 1)
xlRange1.Value = "工場番号"
MRComObject(xlRange1, True)
While sqlReader.Read
xlRange1 = xlCells(i + 1, 1)
xlRange1(xlCells(i + 1, 1)).Select()
xlRange1.Value = sqlReader("入力_工場番号")
MRComObject(xlRange1, True)
i += 1
End While
excel.DisplayAlerts = False
xlsheet.SaveAs(wstrPath)
'Select Case Val(excel.Version)
'Case 9
'xlbook.SaveAs(Filename:=wstrPath)
'Case 12
'xlbook.SaveAs(Filename:=wstrPath, FileFormat:=56)
'End Select
'MRComObject(xlsheet, True)
excel.DisplayAlerts = True
MRComObject(xlsheet)'xlSheet の解放
MRComObject(xlsheets)'xlSheets の解放
xlbook.Close()'xlBook を閉じる
MRComObject(xlbook)'xlBook の解放
MRComObject(xlbooks)'xlBooks の解放
excel.Quit()'Excelを閉じる
MRComObject(excel)'excel を解放
Private Function Func_Excelチェック(ByVal arg As String) As Boolean
Dim excel As New Excel.Application
Dim xlbooks As Excel.Workbooks = excel.Workbooks
Dim xlbook As Excel.Workbook
excel.Visible = False
excel.Application.DisplayAlerts = False
Try
If System.IO.File.Exists(arg) = True Then
xlbook = xlbooks.Open(arg)
xlbook.SaveAs(arg, FileFormat:=42, CreateBackup:=False)
MRComObject(xlbook, True)
Return True
Else
Return True
End If
Catch ex As Exception
MessageBox.Show("")
Return False
Finally
xlbooks.Close()
MRComObject(xlbooks, True)
excel.Quit()
MRComObject(excel, True)
End Try
End Function
こんばんは。
COMがすべてのオブジェクトに対して、参照カウンタを持っているので、全部開放しないとダメです・・・。
Dim xlCells As Excel.Range
Dim xlRange1 As Excel.Range
ここも含めて、参照したものはすべて開放してください。
結構困るんですよね・・・これ。