【问题标题】:Powershell: how to reference to a specific Excel application if more than one Excel application are openPowershell:如果打开了多个 Excel 应用程序,如何引用特定的 Excel 应用程序
【发布时间】:2014-08-01 23:54:58
【问题描述】:
假设我输入这样的代码:
$excel = [Runtime.InteropServices.Marshal]::GetActiveObject("Excel.Application")
只有当我只打开一个 Excel 应用程序时它才会起作用。如果我打开了两个 Excel 应用程序,$excel 可能会引用错误的应用程序。有没有办法引用特定的 Excel 应用程序,例如,根据其文件名或窗口标题?
【问题讨论】:
标签:
excel
powershell
runtime
【解决方案1】:
我用这个:
$sig = @"
[DllImport("user32.dll", SetLastError=true)]
public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
"@
Add-Type -MemberDefinition $sig -Namespace User32 -Name Util -UsingNamespace System.Text
$p=0
[User32.util]::GetWindowThreadProcessId($MSExcel.HWND, [ref]$p) |out-null
Get-Process -id $p | Stop-Process
老实说,我不记得我从哪里得到它(我确定不是我写的),但它满足了我的需要,能够结束我的脚本专门启动的 Excel 窗口。