In an EXCEL-macro I want to copy a selected range to a WORD-document table. I know how to do this, creating a new WORD-document (target). But I want to check if there are already open WORD-documents from which I can select a target.
I found code for looping through all open EXCEL-Applications from within a EXCEL-Macro. I modified the code from Florent Breheret as given below.
What are the missing class names, indicated by "???" in the code, to look for WORD-documents?
Thank you in advance! Immanuel
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
'Test my code
Private Sub GetWordInstances_Test()
Dim wd As Word.Application
Dim i, cnt As Integer
cnt = 0
For Each wd In GetWordInstances()
cnt = cnt + 1
Debug.Print wd.Application.Name, cnt
For i = 1 To wd.Documents.Count
Debug.Print wd.Documents(i).FullName, i
Next i
Next
End Sub
'Getting open WORD instances from within EXCEL-VBA
Public Function GetWordInstances() 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 GetWordInstances = New Collection
Do
hwnd = FindWindowExA(0, hwnd, "OpusApp", vbNullString)
If hwnd = 0 Then Exit Do
hwnd2 = FindWindowExA(hwnd, 0, "???", vbNullString)
hwnd3 = FindWindowExA(hwnd2, 0, "???", vbNullString)
'hand over found WORD application to collection
If AccessibleObjectFromWindow(hwnd3, &HFFFFFFF0, guid(0), acc) = 0 Then
GetWordInstances.Add acc.Application
End If
Loop
End Function