Option Explicit
#If VBA7 Then
Private Declare PtrSafe Sub Sleep Lib "kernel32.dll" (ByVal dwMilliseconds As Long)
#Else
Private Declare Sub Sleep Lib "kernel32.dll" Alias "Sleep" (ByVal dwMilliseconds As Long)
#End If
#If VBA7 Then
Public Sub UIAutomation_Fill_First_Form_Field(AcrobatHwnd As LongPtr, fieldValue As String)
#Else
Public Sub UIAutomation_Fill_First_Form_Field(AcrobatHwnd As LongPtr, fieldValue As String)
#End If
Dim UIAuto As IUIAutomation
Dim AcrobatMain As IUIAutomationElement
Dim ControlTypeCond As IUIAutomationCondition
Dim Document As IUIAutomationElement
Dim Fields As IUIAutomationElementArray
Dim field As IUIAutomationElement
Dim i As Long
'Create UIAutomation object
Set UIAuto = New CUIAutomation
'Get the main Acrobat window of the displayed PDF. This is a Window control with the class name AcrobatSDIWindow
Set AcrobatMain = UIAuto.ElementFromHandle(ByVal AcrobatHwnd)
'Get the main document control
'ControlType = UIA_DocumentControlTypeId (0xC36E) 50030
Set ControlTypeCond = UIAuto.CreatePropertyCondition(UIA_ControlTypePropertyId, UIA_DocumentControlTypeId)
Do
Set Document = AcrobatMain.FindFirst(TreeScope_Descendants, ControlTypeCond)
DoEvents
Sleep 200
Loop While Document Is Nothing
'Get all Edit controls within the document
'ControlType: UIA_EditControlTypeId (0xC354)
Set ControlTypeCond = UIAuto.CreatePropertyCondition(UIA_ControlTypePropertyId, UIA_EditControlTypeId)
Set Fields = Document.FindAll(TreeScope_Subtree, ControlTypeCond)
Debug.Print Fields.Length 'includes read-only fields
Sleep 200
'Fill the first Edit control field which isn't read-only
i = 0
Do While i < Fields.Length - 1
Set field = Fields.GetElement(i)
If Not field.GetCurrentPropertyValue(UIA_ValueIsReadOnlyPropertyId) Then
field.SetFocus
SendKeys "^a{DELETE}", True 'clear any existing field value
Sleep 100
DoEvents
SendKeys fieldValue
DoEvents
Sleep 100
Exit Do
End If
i = i + 1
Loop
'Ctrl+S to save the modified PDF
AcrobatMain.SetFocus
SendKeys "^(s)", True
End Sub