J
John Haldi
I have a simple class which tried to connect to an already running instance
of Excel. Here is my code:
Public Class PatriotExcelLink
Private myExcel As Excel.Application
Private myWorkbook As Excel.Workbook
Private mySheet As Excel.Worksheet
Private myRange As Excel.Range
Public Sub ConnectToExcelWorkbook(ByVal WorkbookName As String)
Try
Dim myExcelProcesses As Process() =
Process.GetProcessesByName("Excel")
If myExcelProcesses.Length > 0 Then
Dim myProcess As Process
For Each myProcess In myExcelProcesses
myExcel =
System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application")
Dim wbCount As Integer = myExcel.Workbooks.Count
Dim i As Integer
For i = 1 To wbCount
If myExcel.Workbooks(i).Name = WorkbookName Then
myWorkbook = myExcel.Workbooks(i)
Exit For
End If
Next
Next
If myWorkbook Is Nothing Then
myExcel.Workbooks.Open(WorkbookName)
End If
Else
myExcel = CreateObject("Excel.Application")
myExcel.Workbooks.Open(WorkbookName)
End If
myExcel.Visible = True
myWorkbook = myExcel.Workbooks(1)
myWorkbook.Activate()
Catch ex As Exception
MsgBox("An unhandled error occurred in
PatriotExcelLink.ConnectToExcelWorkbook: " & ex.Message)
End Try
End Sub
End Class
My question is this: GetActiveObject takes "Excel.Application" as the value
for progID. How can I cycle through multiple instances of Excel running in
order to connect to the one that has my specific File opened already? When I
run this code as is, the GetActiveObject returns the first instance every
time.
Many thanks,
John
of Excel. Here is my code:
Public Class PatriotExcelLink
Private myExcel As Excel.Application
Private myWorkbook As Excel.Workbook
Private mySheet As Excel.Worksheet
Private myRange As Excel.Range
Public Sub ConnectToExcelWorkbook(ByVal WorkbookName As String)
Try
Dim myExcelProcesses As Process() =
Process.GetProcessesByName("Excel")
If myExcelProcesses.Length > 0 Then
Dim myProcess As Process
For Each myProcess In myExcelProcesses
myExcel =
System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application")
Dim wbCount As Integer = myExcel.Workbooks.Count
Dim i As Integer
For i = 1 To wbCount
If myExcel.Workbooks(i).Name = WorkbookName Then
myWorkbook = myExcel.Workbooks(i)
Exit For
End If
Next
Next
If myWorkbook Is Nothing Then
myExcel.Workbooks.Open(WorkbookName)
End If
Else
myExcel = CreateObject("Excel.Application")
myExcel.Workbooks.Open(WorkbookName)
End If
myExcel.Visible = True
myWorkbook = myExcel.Workbooks(1)
myWorkbook.Activate()
Catch ex As Exception
MsgBox("An unhandled error occurred in
PatriotExcelLink.ConnectToExcelWorkbook: " & ex.Message)
End Try
End Sub
End Class
My question is this: GetActiveObject takes "Excel.Application" as the value
for progID. How can I cycle through multiple instances of Excel running in
order to connect to the one that has my specific File opened already? When I
run this code as is, the GetActiveObject returns the first instance every
time.
Many thanks,
John