重写程序以搜索打开的Excel工作簿

时间:2014-02-26 18:19:16

标签: excel visual-studio

我编写了以下过程以检查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

End Sub

1 个答案:

答案 0 :(得分:1)

您尝试查找Excel实例的异常可能是因为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