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?

mklement0
  • 382,024
  • 64
  • 607
  • 775
Borek Bernard
  • 50,745
  • 59
  • 165
  • 240
  • 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: http://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. – Ian Gilroy Jun 18 '12 at 11:49
  • Just to complement Ian's answer: $Excel = [Runtime.Interopservices.Marshal]::GetActiveObject('Excel.Application') will retrieve the existing instance of Excel. – David Brabant Jun 18 '12 at 12:42
  • Thanks. However, I've just tried that and then execute `$Excel.Visiable = $true` - it still opened a new Excel window. – Borek Bernard Jun 18 '12 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`. – mklement0 Feb 19 '22 at 19:04

2 Answers2

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.

Ayush
  • 3,989
  • 1
  • 26
  • 34
user2587683
  • 191
  • 2
  • 6
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.

Community
  • 1
  • 1
Angshuman Agarwal
  • 4,796
  • 7
  • 41
  • 89