Hi all,
I'm trying to access the most recent instance of Excel so I can paste data. What works for me is if Excel isn't already opened, I open it and can paste the data where I want to. What isn't working for me is if there are multiple instances of Excel open.
I'll explain: Say I have 3 instances of Excel opened, each with one workbook. Instance 1 = Book1, instance 2 = Book2, and instance 3 = Book3. I want to paste my data to Book3, since that's the most-recently-opened instance. Here's my code:
The AppActivate (line 10) does indeed activate the correct instance of Excel (Book3), but xlApp (line 13) ends up getting assigned to the Book1 instance, and my data ends up pasting there, even though Book3 is the visible/active workbook.
Can somebody please help me understand what's going on here, and how to fix it? I would appreciate some code, because I'm fairly new to .NET and can't always understand if somebody says, "Just use this and this..." Thanks in advance for any and all help. I've been working on this for two days and it's driving me crazy trying to figure out what's going on!
I'm trying to access the most recent instance of Excel so I can paste data. What works for me is if Excel isn't already opened, I open it and can paste the data where I want to. What isn't working for me is if there are multiple instances of Excel open.
I'll explain: Say I have 3 instances of Excel opened, each with one workbook. Instance 1 = Book1, instance 2 = Book2, and instance 3 = Book3. I want to paste my data to Book3, since that's the most-recently-opened instance. Here's my code:
Code:
' Get (array of) all running Excel processes
Dim xlProcesses As Process() = Process.GetProcessesByName("excel")
If xlProcesses.Length = 0 Then ' If Excel isn't found
Dim xL As Process = Process.Start("excel") ' Open Excel
Sleep(500) ' Wait for Excel to start before continuing
Else
' Activate the most-recently-active workbook in the most recent instance of Excel
' (processes are listed in the order of most-recently-opened first).
AppActivate(xlProcesses(0).Id)
Try
' Assign the active Excel process
xlApp = CType(Marshal.GetActiveObject("Excel.Application"), Excel.Application)
Catch ex As Exception
MsgBox(ex.Message)
Exit Sub
End Try
End If
' Get filename (only, no path) for current window
xlFileName = xlApp.ActiveWindow.Caption
Can somebody please help me understand what's going on here, and how to fix it? I would appreciate some code, because I'm fairly new to .NET and can't always understand if somebody says, "Just use this and this..." Thanks in advance for any and all help. I've been working on this for two days and it's driving me crazy trying to figure out what's going on!
Comment