I need to get a table from an Excel worksheet. Sometimes I know the worksheet that contains the table, other times I might know it's going to be in one of a handful of worksheets, and still other times I might not even know what workbook it's in.
To me, this seemed like a good place to use an overloads function. What I did was create the following overloaded function which recursively calls itself to dig down into each "level" of the input object's hierarchy so that it allows me to look for the table using a variety of input objects.
I'd like to get some feedback on this solution; is it acceptable practice? Is this a good use of overloading? Is there a better (more practical, more efficient, etc.) way to do it?
Note 1: I've omitted class members not related to this question.
Note 2: I haven't gotten deep enough into debugging to add any specific error handling to the try/catch structure, but I do plan to add more specific "catches" eventually.
Imports Microsoft.Office
Imports Microsoft.Office.Interop.Excel
Imports System.Windows.Forms
Imports System.Runtime.InteropServices
Public Class MyExcel
Public Overloads Function GetTable(ByVal SearchName As String, ByVal SearchSheets() As Worksheet, Optional ByVal ExactMatch As Boolean = False) As ListObject
If Not ExactMatch Then SearchName = "*" & SearchName & "*"
Try
For Each ws As Worksheet In SearchSheets
For Each lo As ListObject In ws.ListObjects
If lo.Name Like SearchName Then Return lo
Next
Next
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
Return Nothing
End Function
Public Overloads Function GetTable(ByVal SearchName As String, ByVal SearchBooks() As Workbook, Optional ByVal ExactMatch As Boolean = False) As ListObject
Dim loFound As ListObject
Dim wsList As New List(Of Worksheet)
Try
For Each wb In SearchBooks
For Each ws In wb.Worksheets
wsList.Add(ws)
Next
loFound = Me.GetTable(SearchName:=SearchName, SearchSheets:=wsList.ToArray, ExactMatch:=ExactMatch)
If Not loFound Is Nothing Then Return loFound
Next
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
Return Nothing
End Function
Public Overloads Function GetTable(ByVal SearchName As String, ByVal SearchApps() As Microsoft.Office.Interop.Excel.Application, Optional ByVal ExactMatch As Boolean = False) As ListObject
Dim loFound As ListObject
Dim wbList As New List(Of Workbook)
Try
For Each app In SearchApps
For Each wb In app.Workbooks
wbList.Add(wb)
Next
loFound = Me.GetTable(SearchName:=SearchName, SearchBooks:=wbList.ToArray, ExactMatch:=ExactMatch)
If Not loFound Is Nothing Then Return loFound
Next
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
Return Nothing
End Function
End Class