0

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

1 回答 1

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()
于 2013-09-10T16:33:56.823 回答