I am searching for a string in a table inside a PDF file using a VBA script. The script is working when called from Word but not when called from Excel.
My PDF has many tables and the goal is to get the table number of the table containing a specific string.
Sub FindTableno()
Dim oTbl As Table
Dim oRow As Row
Dim oCell As Cell
Dim tblno As Integer
On Error Resume Next
' Create a "FileDialog" object as a File Picker dialog box.
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
Dim sfileName As String
With fd
.AllowMultiSelect = False
.Filters.Clear
.Title = "Select a PDF File"
.Filters.Add "All PDF Documents", "*.pdf?", 1
If .Show = True Then
sfileName = Dir(.SelectedItems(1)) ' Get the file.
End If
End With
Application.ScreenUpdating = False
Application.DisplayAlerts = False
If Trim(sfileName) <> "" Then
Dim objWord As Object ' Create a Word object.
Set objWord = CreateObject("Word.Application")
objWord.Visible = False ' Do not show the file.
' Create a Document object and open the Word file.
Dim objDoc As Word.Document
Set objDoc = objWord.Documents.Open(FileName:=fd.InitialFileName & sfileName, Format:="PDF Files", ConfirmConversions:=False)
' Search within tables in selected PDF file
objDoc.Activate
If ActiveDocument.Tables.Count > 0 Then
tblno = 1
For Each oTbl In ActiveDocument.Tables
For Each oRow In oTbl.Rows
For Each oCell In oRow.Cells
oCell.Select
Selection.Find.Execute FindText:="Nutrition Information"
If Selection.Find.Found = True Then
MsgBox (tblno)
Exit Sub
Else
End If
Next
Next
tblno = tblno + 1
Next
End If
MsgBox ("Not Found, Total Tables Searched:" & ActiveDocument.Tables.Count)
End If
Dim X As Variant
X = Shell("powershell.exe kill -processname winword", 1)
End Sub