从 VBS 打开或激活 Excel 中的工作簿

Opening or activating workbook in Excel from VBS

我正在编写一个小的 VBScript 来执行以下操作:

  1. 检查Excel是否打开;如果不打开它。
  2. 如果 Excel 已打开,请检查特定工作簿是否已打开。
  3. 如果工作簿处于打开状态,则将其激活;如果没有,打开它。

到目前为止,我已经能够编写以下代码:

ExcelFileName = "....xlsx"

On Error Resume Next
Set xl = GetObject(, "Excel.Application")
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
    Set wb=obj
    xl.DisplayAlerts = False
    wb.Save
    Exit For
    End If
Next

If wb Is Nothing Then
    xl.Workbooks.Open("C:\...")
End If

Set xl = Nothing
Set wb = Nothing

但如果 Excel 尚未打开,它会静默地打开新实例失败。

GetObject 在为您提供 Excel 的 运行 实例或导致错误时表现正常。如果出现错误(Excel 而不是 运行),请使用 CreateObject 创建 Excel.

的新实例

使用 GetObject 打开文件。

set wb = GetObject("c:\folder\excel.xls")

COM 会找出需要完成的工作。一行即可满足您的三个要求。

这是 VB 在使用带有文件名的 GetObject 时要求 COM 执行的操作的内容。

BindMoniker

Locates an object by means of its moniker, activates the object if it is inactive, and retrieves a pointer to the specified interface on that object.

HRESULT BindMoniker( LPMONIKER pmk, DWORD grfOpt, REFIID iidResult, LPVOID FAR * ppvResult );