En este artículo, veremos cómo buscar y resaltar una cadena de texto en un archivo PDF con Excel VBA. Veremos dos ejemplos, uno que funciona con Acrobat Reader y un segundo que debe usarse si tiene una versión con licencia de Acrobat Pro.
Ejemplo 1: uso de SendKeys en Acrobat Reader
En esto, simplemente abrimos el archivo PDF especificado usando FollowHyperlink. A continuación, usaremos la función SendKeys para llamar primero a la búsqueda (usando Ctrl + F), escribir la cadena de búsqueda y enviar la tecla «enter» para realizar la búsqueda real. Aquí está el código completo. Puedes seguir los comentarios en el código.
Sub SearchStringInPDF()
Dim PDF_path As String
Dim searchString As String
Dim waitTime As Date
Application.DisplayAlerts = False
'Make sure to provide a complete path to the PDF here
'if your Excel and PDF are in separate folders
PDF_path = "search.pdf"
'Your search string - case-insensitive, as in actual PDF search
searchString = "sample"
'Open the pdf file
ThisWorkbook.FollowHyperlink PDF_path
'Wait time for a couple of seconds for the PDF file to fully load
waitTime = Now
While DateDiff("s", waitTime, Now) &> 2
DoEvents
Wend
'Send "CTRL + F" keys to the opened PDF to invoke find within that file
'The second argument "true" implies that Excel will wait for the keys to be processed
'before returning control to the macro.
SendKeys "^f", True
'Type the search string in the find box that opens
SendKeys searchString, True
'Hit enter to perform the search
SendKeys "{Enter}", True
Application.DisplayAlerts = True
End Sub
Cuando ejecuta este código, el archivo PDF recibe el foco y la cadena de búsqueda se resalta, así
Tenga en cuenta que SendKeys puede no ser confiable, especialmente porque literalmente envía el comando (teclas) a la ventana activa. Entonces, si accidentalmente activa otra ventana mientras ejecuta la macro, no dará los resultados deseados. No siempre es posible garantizar que la ventana activa sea la ventana prevista.
La mejor solución siempre es optar por el enfoque API, como puede ver en el siguiente ejemplo. La API usa un objeto para identificar y apuntar a una ventana específica. Entonces, cuando usa objetos, puede estar seguro de que está interactuando con la ventana correcta, ya sea que esté activa o inactiva.
Ejemplo 2: uso del objeto de aplicación de Adobe para Acrobat Pro
Si tiene la versión con licencia de Acrobat Pro, debe usar el código a continuación. Primero creamos los objetos requeridos, abrimos el PDF, lo traemos y luego buscamos la cadena usando la función FindText
Sub searchUsingAcrobatPro()
Dim searchString As String
Dim PDF_path As String
Dim appObj As Object, AVDocObj As Object
searchString = "PDF"
PDF_path = "search.pdf"
'Check if the file exists.
If Dir(PDF_path) = "" Then
MsgBox "File not found..."
Exit Sub
End If
On Error Resume Next
'Create Adobe Application object.
Set appObj = CreateObject("AcroExch.App")
'Check for any errors.
If Err.Number & < & > 0 Then
MsgBox "Error in creating the Adobe Application object..."
Set appObj = Nothing
Exit Sub
End If
'Create the AVDoc object.
Set AVDocObj = CreateObject("AcroExch.AVDoc")
'Check for any errors.
If Err.Number & < & > 0 Then
MsgBox "Error in creating the AVDoc object..."
Set AVDocObj = Nothing
Set appObj = Nothing
Exit Sub
End If
On Error GoTo 0
'Open the PDF file and check if the open was successful.
If AVDocObj.Open(PDF_path, "") = True Then
'Bring the PDF file to the front.
AVDocObj.BringToFront
'Search for the string and check if the the string was found.
'If text is found, it will be highlighted (PDF is already in focus)
If AVDocObj.findtext(searchString, False, False, False) = False Then
'If text was not found, close the PDF file and perform clean-up
AVDocObj.Close True
appObj.Exit
'Release the objects.
Set AVDocObj = Nothing
Set appObj = Nothing
MsgBox "The string not found in the PDF file..."
End If
Else
'PDF file failed to open
appObj.Exit
'Release the objects.
Set AVDocObj = Nothing
Set appObj = Nothing
MsgBox "Could not open the PDF file..."
End If
End Sub
El texto se resalta de nuevo como antes. Sin embargo, aquí no verá el cuadro de texto de búsqueda en la esquina superior derecha.
Ahora echemos un vistazo más de cerca a la función FindText. La sintaxis de la función se da a continuación.
Buscar texto(szText como cadena, bCaseSensitive como largo, bWholeWordsOnly como largo, bReset como largo) Si es booleano
szTexto: Texto a buscar
sensibilidad a mayúsculas y minúsculas: si la búsqueda debe distinguir entre mayúsculas y minúsculas (True distingue entre mayúsculas y minúsculas)
b Solo palabras completas: Coincidir con la palabra completa o incluso parte de una palabra (Verdadero es coincidir con la palabra completa)
bReiniciar: Un número positivo inicia la búsqueda desde la primera página del documento. Si 0, es comienza en la página actual.
valor de beneficio: la función devuelve verdadero si se encuentra la cadena especificada. De lo contrario se devuelve falso
La API de Adobe contiene muchas más funciones útiles que puede usar para interactuar con un archivo PDF usando Excel VBA. Un documento completo está disponible en el sitio de Abode
Esta es una forma más eficiente y confiable de buscar un archivo PDF y se recomienda usarla.
Lea más sobre el texto y las cadenas de Excel aquí:
Procesamiento y manipulación de cadenas de Excel VBA
Fórmulas y funciones de Excel, buscar texto dentro de otro texto, buscar ()