See if this alternate would be acceptable. Note that all objects used are disposed of properly which leads to more code in the long run.
Example call
Dim demo As New ExcelIterate With
{
.FileName = IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Countries.xlsx"),
.SheetName = "countrylist"
}
Dim results As Object(,) = demo.OpenExcelIterate("A9", "B15")
Class
Option Strict On
Option Infer Off
Imports Excel = Microsoft.Office.Interop.Excel
Imports Microsoft.Office
Imports System.Runtime.InteropServices
Public Class ExcelIterate
Public Property FileName As String
Public Property SheetName As String
Public Function OpenExcelIterate(ByVal StartCell As String, ByVal LastCell As String) As Object(,)
Dim Results(,) As Object = Nothing
If IO.File.Exists(FileName) Then
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 xlCells 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
Dim xlUsedRange As Excel.Range = xlWorkSheet.Range(StartCell, LastCell)
Dim DecimalTest As Decimal = 0
Try
Results = CType(xlUsedRange.Value(Excel.XlRangeValueDataType.xlRangeValueDefault), Object(,))
Finally
ReleaseComObject(xlUsedRange)
End Try
Else
MessageBox.Show(SheetName & " not found.")
End If
xlWorkBook.Close()
xlApp.UserControl = True
xlApp.Quit()
ReleaseComObject(xlCells)
ReleaseComObject(xlWorkSheets)
ReleaseComObject(xlWorkSheet)
ReleaseComObject(xlWorkBook)
ReleaseComObject(xlWorkBooks)
ReleaseComObject(xlApp)
Else
MessageBox.Show("'" & FileName & "' not located. Try one of the write examples first.")
End If
Return Results
End Function
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