7

All examples that automate Excel through PowerShell start with this line:

PS> $Excel = New-Object -Com Excel.Application

This seems to be handling a new instance of Excel, e.g. running $Excel.Visible = $true will show an empty, blank Excel window, not switch to the existing workbook.

If there is already an instance of Excel running, is there a way to connect to it?

4
  • Do you need to connect to a specific instance of Excel as represented by a specific window? If not you could also look at accessing a running Excel instance like this: support.microsoft.com/kb/316126. The KB article uses C# but the calls (System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application"), for example) should be pretty easy to translate. Commented Jun 18, 2012 at 11:49
  • Just to complement Ian's answer: $Excel = [Runtime.Interopservices.Marshal]::GetActiveObject('Excel.Application') will retrieve the existing instance of Excel. Commented Jun 18, 2012 at 12:42
  • Thanks. However, I've just tried that and then execute $Excel.Visiable = $true - it still opened a new Excel window. Commented Jun 18, 2012 at 14:26
  • @BorekBernard, [Runtime.Interopservices.Marshal]::GetActiveObject('Excel.Application') does appear to work, assuming the existing instance was created by the same user, as user2587683's answer states. Also note that you mistyped .Visible as .Visiable. Commented Feb 19, 2022 at 19:04

2 Answers 2

16

Instead of the usual New-Object -ComObject excel.application us this

$excel = [Runtime.Interopservices.Marshal]::GetActiveObject('Excel.Application')

Rest stays the same.

One downside. You will only get the excel "instances" started by the same user that will initiate the ps1.

Sign up to request clarification or add additional context in comments.

1 Comment

Lovely answer. But how would you account for having multiple excel, assuming you knew the process Id of the specific excel you want? This is the dilemma I’m in
1

Yes, you can access the COM object via HWND [Window handle] using this WIN32 API (AccessibleObjectFromWindow).

(See a SO post sample here of using this api via C#)

.

You may have to write an assembly in C# and/or manipulate P/Invoke calls via Powershell.

You may give a shot at it & see how it goes.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.