是否可以从excel Vba检测并列出所有打开的PDF文件?我知道我可以检查特定的已知PDF文件和路径,但在这种情况下,文件名和路径将不知道。
由于
答案 0 :(得分:0)
我在Ryan Wildry的评论中提醒我,我可以使用AHK来做这样的事情。这是我最终使用的代码:
首先,我在VBA中设置了一个正则表达式模式,以便了解PDF窗口标题的显示方式。使用了我从Web上为以前的应用程序提取的几个函数。
主要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,循环遍历每个打开的窗口,检查它是否与定义的模式匹配,然后将其附加到字符串。该字符串被发送到剪贴板,然后VBA读取并拆分成一个数组供我使用。
我确信可能有一种更有效的方式,但这是一种有趣的方式,也是我可以组合在一起的唯一方式。