0

编辑:在我将特定的 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 窗口一起工作?

4

1 回答 1

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 实例。您需要终止该实例才能附加到下一个实例(请参见此处)。但是,由于在已运行的实例中打开工作簿是默认设置,因此上述方法应该适用于大多数情况。

于 2013-07-09T21:25:45.763 回答