如何获取所有应用程序对象

如何获取所有应用程序对象

本文介绍了启动多个excel实例后,如何获取所有应用程序对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我想使用类似于
GetObject(,Excel.Application)的东西来获取我创建的应用程序。

Basically, I want to use something similar toGetObject(,"Excel.Application") to get back the application I created.

我打了几次 CreateObject(Excel.Application)来创建新的excel实例。后来由于调试和编码,VBA项目被重置。 Application对象变量丢失。但是excel仍然在后台运行。内存泄漏情况。

I called a few times of CreateObject("Excel.Application") to create new excel instances. Later somehow VBA project get reset due to debuging and coding. The Application object variable got lost. But the excel is still running in background. Kind of memory leak situation.

我只想重新附加到他们。
重新使用(以此方式优先)或关闭它们。

I just want to re-attach to them.Either re-use(prefered this way) or close them.

推荐答案

列出正在运行的Excel实例:

To list the running instances of Excel:

#If VBA7 Then
  Private Declare PtrSafe Function AccessibleObjectFromWindow Lib "oleacc" ( _
    ByVal hwnd As LongPtr, ByVal dwId As Long, riid As Any, ppvObject As Object) As Long

  Private Declare PtrSafe Function FindWindowExA Lib "user32" ( _
    ByVal hwndParent As LongPtr, ByVal hwndChildAfter As LongPtr, _
    ByVal lpszClass As String, ByVal lpszWindow As String) As LongPtr
#Else
  Private Declare Function AccessibleObjectFromWindow Lib "oleacc" ( _
    ByVal hwnd As Long, ByVal dwId As Long, riid As Any, ppvObject As Object) As Long

  Private Declare Function FindWindowExA Lib "user32" ( _
    ByVal hwndParent As Long, ByVal hwndChildAfter As Long, _
    ByVal lpszClass As String, ByVal lpszWindow As String) As Long
#End If

Sub Test()
  Dim xl As Application
  For Each xl In GetExcelInstances()
    Debug.Print "Handle: " & xl.ActiveWorkbook.FullName
  Next
End Sub

Public Function GetExcelInstances() As Collection
  Dim guid&(0 To 3), acc As Object, hwnd, hwnd2, hwnd3
  guid(0) = &H20400
  guid(1) = &H0
  guid(2) = &HC0
  guid(3) = &H46000000

  Set GetExcelInstances = New Collection
  Do
    hwnd = FindWindowExA(0, hwnd, "XLMAIN", vbNullString)
    If hwnd = 0 Then Exit Do
    hwnd2 = FindWindowExA(hwnd, 0, "XLDESK", vbNullString)
    hwnd3 = FindWindowExA(hwnd2, 0, "EXCEL7", vbNullString)
    If AccessibleObjectFromWindow(hwnd3, &HFFFFFFF0, guid(0), acc) = 0 Then
      GetExcelInstances.Add acc.Application
    End If
  Loop
End Function

这篇关于启动多个excel实例后,如何获取所有应用程序对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 06:16