重写程序search打开excel的小工具

我编写了下面的过程来检查打开的Excel实例,然后检查是否打开了特定的工作簿,是否打开工作簿,然后转到选定的工作表。

程序工作正常,但我并不特别满意我写的方式。 例如,在以下几行中,该过程将检查工作簿是否打开,如果不是,则会跳出该path并使用Catch将其打开。

  Dim xlWBName As String = "2011.1004.Compensation Template" Dim xlBookPath As String = Path.Combine(Directory.GetCurrentDirectory()) xlApp.Visible = True Try 'get the opened workbook xlBook = xlApp.Workbooks(xlWBName & ".xlsx") Catch ex As Exception 'open it xlBook = xlApp.Workbooks.Open(xlBookPath & "\" & xlWBName & ".xlsx") End Try 

如果尚未打开工作簿,我不想使用Catch作为打开工作簿的方式。 我宁愿使用它作为一个真正的exception,如工作簿不在目录中。 我的问题是,如何重新编写这个程序,以更好地做我想要的。 这是我的整个程序:

Public Sub GoToSheets(sheetName As String)

 Cursor.Current = Cursors.AppStarting frmPleaseWait.Show() Try 'get an existing excel.application object xlApp = CType(GetObject(, "Excel.Application"), Application) Catch ex As Exception 'no existing excel.application object - create a new one xlApp = New Excel.Application End Try Dim xlWBName As String = "2011.1004.Compensation Template" Dim xlBookPath As String = Path.Combine(Directory.GetCurrentDirectory()) xlApp.Visible = True Try 'get the opened workbook xlBook = xlApp.Workbooks(xlWBName & ".xlsx") Catch ex As Exception 'open it xlBook = xlApp.Workbooks.Open(xlBookPath & "\" & xlWBName & ".xlsx") End Try Try xlSheet = CType(CType(xlBook.Sheets(sheetName), Excel.Worksheet), Excel.Worksheet) xlSheet.Activate() frmPleaseWait.Close() System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp) GC.Collect() GC.WaitForPendingFinalizers() GC.Collect() GC.WaitForPendingFinalizers() 'Show curser waiting Cursor.Current = Cursors.WaitCursor Catch ex As Exception 'Catch any other exceptions here MessageBox.Show("An exception occurred while processing the file" & vbNewLine & ex.GetType.ToString, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error) End Try 

结束小组

你正在试图find一个Excel实例的exception可能是因为CType失败并抛出一个InvalidCastException 。 您可以通过避免投射(最初)来避免这种情况:

 Dim xlObject As Object Try 'get an existing excel.application object xlObject = GetObject(, "Excel.Application") Catch ex As Exception ' Some other exception now End Try If Not xlObject Is Nothing Then ' Found something, make the cast xlApp = CType(xlObject, Application) Else ' Did not find anything, create new instance xlApp = New Excel.Application End If 

并检查工作簿是否存在,只需循环查看他们的名字:

 Dim isWbOpen As Boolean For i As Integer = 0 To xlApp.Workbooks.Count - 1 If xlApp.Workbooks(i).Name = xlWBName Then isWbOpen = True Exit For End If Next If isWbOpen Then xlBook = xlApp.Workbooks(xlWBName & ".xlsx") Else xlBook = xlApp.Workbooks.Open(xlBookPath & "\" & xlWBName & ".xlsx") End If