过程打开Excel的多个实例

时间:2013-09-10 15:43:16

标签: vb.net excel

如果打开,我编写了以下过程来检查Microsoft Excel应用程序。该过程正常,但一旦打开工作簿并激活工作表,Excel的第二个实例将尝试打开。

这是我的代码:

Dim xlApp As New Excel.Application
Dim xlBook As Excel.Workbook
Dim xlWBName As String = "2011.1004.Compensation Template"

For Each p As System.Diagnostics.Process In System.Diagnostics.Process.GetProcesses()
    If p.ProcessName <> "EXCEL" Then
        xlApp.Visible = True
        xlBook = xlApp.Workbooks.Open("F:\Test Environment\Compensation Workbook\Compensation Workbook\bin\Debug\" & xlWBName & ".xlsx")
        Dim xlSheet As Excel.Worksheet
        xlSheet = CType(xlBook.Sheets("SummaryWorksheet"), Worksheet)

        xlSheet.Activate()
    End If
Next

1 个答案:

答案 0 :(得分:3)

使用GetObject方法查找已打开的Application对象:

http://msdn.microsoft.com/en-us/library/e9waz863(v=vs.90).aspx

    Dim xlApp As Excel.Application

    Try
        'get an existing excel.application object
        xlApp = GetObject(, "Excel.Application")
    Catch ex As Exception
        'no existing excel.application object - create a new one
        xlApp = New Excel.Application
    End Try

    Dim xlBook As Excel.Workbook
    Dim xlWBName As String = "2011.1004.Compensation Template"


    xlApp.Visible = True
    xlBook = xlApp.Workbooks.Open("F:\Test Environment\Compensation Workbook\Compensation Workbook\bin\Debug\" & xlWBName & ".xlsx")
    Dim xlSheet As Excel.Worksheet
    xlSheet = CType(xlBook.Sheets("SummaryWorksheet"), Worksheet)

    xlSheet.Activate()