If you want to call GC.Collect, I think it's a good idea to do it like this:
Private Sub Load_Data()
Load_Data_Internal()
GC.Collect()
GC.WaitForPendingFinalizers()
End Sub
Private Sub Load_Data_Internal()
' Excel operations
' If you make all variables local
' There is no need to call ReleaseComObject here.
End Sub
The following are the causes of release leaks:
(1) If there are two periods in one line, a release leak will occur.
Dim xlWorkBook As Excel.Workbook = xlApp.Workbooks.Open(TempPath + "\" + TemplateName1 + ".xlsx")
Dim xlWorkBooks As Excel.Workbooks = xlApp.Workbooks
Dim xlWorkBook As Excel.Workbook = xlWorkBooks.Open(TempPath + "\" + TemplateName1 + ".xlsx")
・
・
・
Marshal.ReleaseComObject(xlWorkBook)
Marshal.ReleaseComObject(xlWorkBooks)
(2) Sheets object is not released
Dim xlWorkSheets As Excel.Sheets = xlWorkBook.Worksheets
(3) When extracting a Sheet object from a WorkSheets object
For ICsn = 1 To qty
xlWorkSheet = CType(xlWorkSheets("UUT_" + CStr(ICsn)), Excel.Worksheet)
・
・
・
Marshal.ReleaseComObject(xlWorkSheet)
Next ICsn
(4) When the Worksheet.Cells property returns a Range object
xlWorkSheet.Cells(54, 1) = ICnum(ICsn - 1)
xlWorkSheet.Cells(Sps + 1, Cnum * 2) = rxmsg(ICsn - 1, Cnum - 1, Sps - 1)
Dim xlCells1 As Excel.Range = xlWorkSheet.Cells
Dim xlRange1 As Excel.Range = xlCells1(54, 1)
xlRange1.Value = = ICnum(ICsn - 1)
Marshal.ReleaseComObject(xlCells1)
Marshal.ReleaseComObject(xlRange1)
Dim xlCells2 As Excel.Range = xlWorkSheet.Cells
Dim xlRange2 As Excel.Range = xlCells2(Sps + 1, Cnum * 2)
xlRange2.Value = rxmsg(ICsn - 1, Cnum - 1, Sps - 1)
Marshal.ReleaseComObject(xlCells2)
Marshal.ReleaseComObject(xlRange2)
(5) Worksheet object has already been released (3)
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp)
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkBook)
'System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkSheet)
Marshal.ReleaseComObject(xlWorkSheets)