1
我編寫了下面的過程來檢查打開的Excel實例,然後檢查是否打開了特定的工作簿,是否打開工作簿,然後轉到選定的工作表。重寫程序以搜索打開的Excel工作簿
該程序正常,但我並不特別滿意我寫的方式。例如,在以下幾行中,該過程將檢查工作簿是否已打開,如果未打開,則會跳出該路徑並使用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
,就好像它是不是已經打開,打開工作簿我的方式。我寧願將它用作真正的例外,例如工作簿不在目錄中。我的問題是,如何重新編寫這個程序,以更好地做我想做的事情。這裏是我的整個過程:
公用Sub GoToSheets(SHEETNAME作爲字符串)
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
末次
謝謝,不僅做到了解決我的問題,它實際上運行得更快。 –