打开多个Excel文件并激活它时,检查特定的Excel文件是否打开

Ele*_*dro 0 vbscript

编辑:在我将特定的Excel文件或其窗口放到前面之前,我需要检查它是否正在运行/仍然打开.

旧问题:我想在前面设置一个特定的Excel窗口.

使用此VBScript代码,我可以按名称激活一个Excel窗口.但是由于打开了多个Excel窗口,它不再起作用.在这种情况下,它将找不到所需的窗口,并且无法检查它是否打开.所以它总是会说ExcelFileName没有打开.

Set WshShell = WScript.CreateObject ("WScript.Shell")
if WshShell.AppActivate(ExcelFileName) = True then
    wscript.echo ExcelFileName & " is opened."
    WshShell.sendkeys "%x" 'in Excel 2003 this would had opened the extra-menu-droplist of the menu-bar. Now it just activates Excel.
else
    wscript.echo ExcelFileName & " is not open."
End if
Run Code Online (Sandbox Code Playgroud)

如何使其与多个打开的Excel窗口一起使用?

Ans*_*ers 6

所以你想检测一个具有给定名称的工作簿是否被打开?这可以在VBScript中像这样完成:

ExcelFileName = "some.xlsx"

On Error Resume Next
Set xl = GetObject(, "Excel.Application")  'attach to running Excel instance
If Err Then
  If Err.Number = 429 Then
    WScript.Echo "Workbook not open (Excel is not running)."
  Else
    WScript.Echo Err.Description & " (0x" & Hex(Err.Number) & ")"
  End If
  WScript.Quit 1
End If
On Error Goto 0

Set wb = Nothing
For Each obj In xl.Workbooks
  If obj.Name = ExcelFileName Then  'use obj.FullName for full path
    Set wb = obj
    Exit For
  End If
Next
If wb Is Nothing Then
  WScript.Echo "Workbook not open."
  WScript.Quit 1
End If
Run Code Online (Sandbox Code Playgroud)

GetObject但是,只能附加到首先启动的Excel实例.您需要终止该实例以便能够附加到下一个实例(请参阅此处).但是,由于它是在已经运行的实例中打开工作簿的默认设置,因此上述内容适用于大多数情况.