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

时间:2013-07-09 13:37:04

标签: 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

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

1 个答案:

答案 0 :(得分: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

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

相关问题