代码中引用的 Excel 工作簿在任务栏中无处可见

Referenced Excel workbook in the code is nowhere to be seen in taskbar

我正在尝试使用 VBA 从 powerpoint 打开工作簿。虽然工作簿对象正在设置,但工作簿无处可见。 [为了清楚起见,请参阅末尾的快照]

代码:

Public Path As String

Sub CheckThisSub()

  Path = ActivePresentation.Path
  Debug.Print (Path & "\" & "QC_Log.xlsm") 'prints D:\QC\Test\QC_Log.xlsm

  Dim QCWbk As New Excel.Workbook
  Set QCWbk = Excel.Workbooks.Open(Path & "\" & "QC_Log.xlsm")
  'QCWbk is getting set but the excel QC_Log.xlsm is nowhere to be seen.

  Debug.Print QCWbk.Name                   'prints QC_Log.xlsm
  QCWbk.Windows.Item(1).Visible = True

' Rest of code

End sub

快照:

因此,创建一个 Excel 会话可以通过不同的方式完成。

  1. 由于您将初始声明从 Dim QCWbk As Excel.Workbook 修改为 Dim QCWbk As New Excel.Workbook,您的代码问题在于您尝试设置 Excel 应用程序的方式。您的代码尝试设置工作簿,而不是 Excel 应用程序。从你的开始的一段工作代码应该是下一个:
Dim QCWbk As New Excel.Workbook, wb as Excel.Workbook, Path As String 'Using New the Excel COM object is already instantiated:

Path = ActivePresentation.Path
Set wb = QCWbk.Workbooks.Open(Path & "\" & "QC_Log.xlsm") 'the workbook is set in this way!
QCWbk.Visible = True 
  1. Excel 应用程序无需引用 Excel 库即可轻松创建。这是后期绑定方式,但您无法从提供对象 properties/methods:
  2. 的智能感知中获益
Dim QCWbk As Object, wb as Object, Path As String '

Path = ActivePresentation.Path
Set QCWbk = CreateObject("Excel.Application")
QCWbk.Visible = True
Set wb = QCWbk.Workbooks.Open(Path & "\" & "QC_Log.xlsm") 'the workbook is set in this way!
  1. 您可以在不预先实例化 COM 对象的情况下使用早期绑定。您受益于 Intellisense 优惠,但您必须在第二步中创建实例:
Dim QCWbk As Excel.Workbook, wb as Excel.Workbook, Path As String 'Using New the Excel COM object is already instantiated:

Path = ActivePresentation.Path
Set QCWbk = CreateObject("Excel.Application")
QCWbk.Visible = True 
Set wb = QCWbk.Workbooks.Open(Path & "\" & "QC_Log.xlsm") 'the workbook is set in this way!
  1. 您可以使用下一个代码获取现有的 Excel 打开会话:
Dim QCWbk Excel.Workbook, wb as Excel.Workbook, Path As String

Path = ActivePresentation.Path

On Error Resume Next
 Set QCWbk = GetObject(, "Excel.Application")
 If Err.Number <> 0 Then
     Err.Clear: On Error GoTo 0
     MsgBox "No Excel Open session..."
     Exit Sub 'the code exists if only an open session is required...
 End If
 'Usually in such a case a new session is created (as above). Here is only the part showing how to use an existing session
 Set wb = QCWbk.Workbooks.Open(Path & "\" & "QC_Log.xlsm") 'the workbook is set in this way!
 QCWbk.Visible = True
  1. 如果您知道在特定会话中打开的工作簿的名称,则可以找到打开的 Excel 会话...例如,如果另一个应用程序(例如 SAP)导出这样的工作簿(名为"Book1") 在一个新的session中,你可以这样找到那个session:
Dim Ex As Excel.Application
Set Ex = GetObject("Book1").Application

Debug.Print Application.ActiveWindow.hwnd, Ex.ActiveWindow.hwnd
  1. 最后,您可以使用API(FindWindowEx、IIDFromString 和AccessibleObjectFromWindow)识别所有Excel 个打开的会话,但它有点复杂,需要在特定情况下使用...