检测并列出 excel VBA 所有打开的 PDF 文件

Detect and list all open PDF files from excel VBA

是否可以检测并列出来自 excel Vba 的所有打开的 PDF 文件?我知道我可以检查特定的已知 PDF 文件和路径,但在这种情况下,文件名和路径将是未知的。

谢谢

Ryan Wildry 在评论中提醒我,我可以使用 AHK 来做这样的事情。这是我最终使用的代码:

首先,我在 VBA 中设置了一个正则表达式模式,以便确定 PDF windows 标题的显示方式。使用我从网上提取的几个功能用于以前的应用程序。

主要VBA:

Private Sub Get_PDFs()

    Dim pattern As String
    Dim ahkParamColl As Collection
    Dim windowArr() As String

    'regex pattern to match with open Adobe PDF Files
    pattern = "^(.+)\.pdf - Adobe Reader$"

    'add pattern to AHK parameter collection
    Set ahkParamColl = Nothing
    Set ahkParamColl = New Collection
    ahkParamColl.Add (pattern)

    'run window detection AHK Script
    Call Functions.Run_AHK("Detect All Open Windows.ahk", ahkParamColl)

    'send list to array
    windowArr = Split(GetClipBoardText, Chr(10))

End Sub

调用AHK的函数:

'these are for AHK scripts to run from Excel
Public Const ahk_ScriptsLoc = """C:\Location of Scripts\" 'starts w/a quote
Public Const ahk_PgmLoc = "C:\Location of AHK Pogram\AHK.exe"


Function Run_AHK(AHK_Script_Name As String, Optional Parameters As Collection)

'Call AHK script from VBA
Dim i As Integer
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1
Dim AHKscript As String
Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")

    'set the ahk script string to call
    AHKscript = ahk_PgmLoc & " " & ahk_ScriptsLoc & AHK_Script_Name & """ """

    'add parameters to script string
    If Not Parameters Is Nothing Then
        For Each s In Parameters
            AHKscript = AHKscript & s & """ """
        Next s
    End If

    'run ahk script
    wsh.Run AHKscript, windowStyle, waitOnReturn

End Function

获取剪贴板文本的函数:

Public Function GetClipBoardText()
   Dim DataObj As MsForms.DataObject
   Set DataObj = New MsForms.DataObject

   On Error GoTo Whoa

   '~~> Get data from the clipboard.
   DataObj.GetFromClipboard

   '~~> Get clipboard contents
   myString = DataObj.GetText(1)
   GetClipBoardText = myString

   Exit Function
Whoa:
   If Err <> 0 Then MsgBox "Data on clipboard is not text or is empty"
End Function

主要 AHK(从 Here 截取):

;regex pattern sent from calling application
pattern = %1%

;get all window names and loop through
WinGet windows, List
Loop %windows%
{
    id := windows%A_Index%
    WinGetTitle wt, ahk_id %id%
    ;if window matches pattern, add to list
    IF (RegexMatch(wt,pattern)>0) then
    {
        s .= wt . "`n"
    }
}
;send list to clipboard
Clipboard := s

因此 VBA 宏将设置要发送到 AHK 脚本的正则表达式模式。如果需要,我可以稍后将其用于其他文档类型或命名模式。然后将调用 AHK,它循环遍历每个打开的 window,检查它是否与定义的模式匹配,然后将其附加到字符串。这个字符串被发送到剪贴板,VBA然后读取并拆分成一个数组供我使用。

我确定可能有更有效的方法,但这是一种有趣的方法,也是我可以组合在一起的唯一方法。