【发布时间】:2018-03-17 20:44:27
【问题描述】:
我编写了下面的过程来检查打开的 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 作为打开工作簿的方式。我宁愿将它用于真正的异常,例如工作簿不在目录中。我的问题是,如何重新编写此程序以更好地执行我想要的操作。这是我的整个过程:
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
结束子
【问题讨论】:
标签: excel visual-studio