Here is a basic pattern for working with Excel Interop. Note how there are typed objects e.g. xlApp which are strongly typed and when done are released.
Option Strict On
Option Infer Off
Imports Excel = Microsoft.Office.Interop.Excel
Imports Microsoft.Office
Imports System.Runtime.InteropServices
Public Class Conceptual
Public Property FileName As String
Public Property SheetName As String
Public Property DataSource As Dictionary(Of String, String)
Public Sub New()
End Sub
Public Sub New(ByVal ExcelFile As String, ByVal Sheet As String)
FileName = ExcelFile
SheetName = Sheet
End Sub
Public Sub OpenExcelWriteDict()
Dim Proceed As Boolean = False
Dim xlApp As Excel.Application = Nothing
Dim xlWorkBooks As Excel.Workbooks = Nothing
Dim xlWorkBook As Excel.Workbook = Nothing
Dim xlWorkSheet As Excel.Worksheet = Nothing
Dim xlWorkSheets As Excel.Sheets = Nothing
Dim xlRange1 As Excel.Range = Nothing
Dim xlColumns As Excel.Range = Nothing
xlApp = New Excel.Application
xlApp.DisplayAlerts = False
xlWorkBooks = xlApp.Workbooks
xlWorkBook = xlWorkBooks.Open(FileName)
xlApp.Visible = False
xlWorkSheets = xlWorkBook.Sheets
For x As Integer = 1 To xlWorkSheets.Count
xlWorkSheet = CType(xlWorkSheets(x), Excel.Worksheet)
If xlWorkSheet.Name = SheetName Then
Proceed = True
Exit For
End If
Runtime.InteropServices.Marshal.FinalReleaseComObject(xlWorkSheet)
xlWorkSheet = Nothing
Next
If Proceed Then
For Each Item As KeyValuePair(Of String, String) In DataSource
xlRange1 = xlWorkSheet.Range(Item.Key)
xlRange1.Value = Item.Value
Marshal.FinalReleaseComObject(xlRange1)
xlRange1 = Nothing
Next
xlWorkSheet.SaveAs(FileName)
Else
MessageBox.Show(SheetName & " not located.")
End If
xlWorkBook.Close()
xlApp.UserControl = True
xlApp.Quit()
ReleaseComObject(xlRange1)
ReleaseComObject(xlWorkSheets)
ReleaseComObject(xlWorkSheet)
ReleaseComObject(xlWorkBook)
ReleaseComObject(xlWorkBooks)
ReleaseComObject(xlApp)
End Sub
Private Sub ReleaseComObject(ByVal obj As Object)
Try
If obj IsNot Nothing Then
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
End If
Catch ex As Exception
obj = Nothing
End Try
End Sub
End Class