我正在尝试在实例A上创建VBA脚本,以便在具有临时且不可预测的名称的分层程序生成的Word实例B上复制基本内容,因此我无法使用GetObject(Path ,),因为我没有它,所以可以使用Path获取该实例。
我的临时解决方案是PowerShell从实例A运行此命令以获取所有Windows的名称(标题中带有“ Word”)...并将其存储在VBA变量中以检测该名称是否来自其他实例比实例A:
Get-Process |Where-Object {$_.mainWindowTitle -like "*Word*"} |format-table mainwindowtitle
它可以工作,但是我不敢相信即使有未知路径,也无法直接从VBA中检测到所有正在运行的应用程序实例。
我在VBA中尝试了类似这样的丑陋事情来跨越不同的实例而没有成功:
Sub GetAllInstance()
Dim WordApp As Word.Application, wordInstance As Object
Set WordApp = GetObject(, "Word.Application")
For Each wordInstance In WordApp
MsgBox (wordInstance)
Next wordInstance
End Sub
立即命令告诉我,GetObject仅具有有关实例A的信息,即使在单独的实例上打开了3个文档,也只有1个文档:
?WordApp.Documents.Count
1
修改20/02:
在Cindy的忠告下,我更改了尝试使用流程的方法,并使用以下代码成功检测到运行实例的差异PID:
Sub IsProcessRunning()
Dim process As String
Dim objList As Object
Dim xprocess As Variant
Dim wdApp As Word.Application
process = "Word.exe"
Set objList = GetObject("winmgmts:") _
.ExecQuery("select ProcessID from win32_process where name='" & process & "'")
For Each xprocess In objList
Debug.Print xprocess.ProcessID
AppActivate (xprocess.ProcessID)
Set wdApp = GetObject(, "Word.Application")
Debug.Print wdApp.Workbooks(1).Name
Next xprocess
End Sub
不幸的是,激活应用程序不会清除ROT,我现在正试图找到一种方法来清除它并刷新它,以在ROT中注册新激活的应用程序,并将GetObject与良好实例一起使用。
答案 0 :(得分:1)
终于找到了解决方案! 使用下面的代码,因为我知道我的第三软件在哪里用新实例生成了临时文件,所以我使用HWND和来自user32 lib的GetWindowText搜索文件的名称。它允许我使用完整路径分配GetObject并在来自两个分离实例的两个文档之间进行交互。感谢Cindy和Mathieu的帮助:
' API declaration
Const GW_HWNDNEXT = 2
Private Declare PtrSafe Function GetWindow Lib "user32" (ByVal hWnd As Long, ByVal wCmd As Long) As Long
Private Declare PtrSafe Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Private Declare PtrSafe Function GetClassName Lib "user32" Alias "GetClassNameA" (ByVal hWnd As Long, ByVal lpClassName As String, ByVal nMaxCount As Long) As Long
Private Declare PtrSafe Function GetWindowText Lib "user32" Alias "GetWindowTextA" (ByVal hWnd As Long, ByVal lpString As String, ByVal cch As Long) As Long
Private Sub CommandButton1_Click()
Dim openDoc As Document, sourceDoc As Document, targetDoc As Object
Dim hWndThis As Long
Dim sTitle As String
Dim xTable As Table
''' INITIALIZATION '''
'Assign the source Document
Set sourceDoc = ActiveDocument
'Detect each instance by Window Name, then assign it to different object
hWndThis = FindWindow(vbNullString, vbNullString)
While hWndThis
sTitle = Space$(255)
sTitle = Left$(sTitle, GetWindowText(hWndThis, sTitle, Len(sTitle)))
If sTitle Like "*tmp*.DOC*" Then
FileToOpen = Left(sTitle, Len(sTitle) - 8)
Set targetDoc = GetObject("C:\Users\xxxxx\AppData\Local\Temp" & "\" & FileToOpen)
GoTo EndLoop:
End If
hWndThis = GetWindow(hWndThis, GW_HWNDNEXT)
Wend
EndLoop:
End Sub