Snippets

Dave Masse Copy+Paste Excel to PDF form

Created by Dave Masse last modified
-- Requires AppleScript Toolbox for click support
-- Acrobat and Excel are open at execution time
-- The script is complicated by the fact that this particular PDF form has a different number of rows on the first page than every subsequent page

set columnLetters to {"A", "C", "D", "E", "F"}
set currentPage to 1
set pagebreakCountFirst to 17
set pagebreakCountSubsequent to 18
set pagebreakExtraTabs to 2
set rowCount to getRowCount()

set currentRow to 1

-- Create the corresponding number of field rows in Acrobat
activate application "Adobe Acrobat Reader DC"
tell application "System Events" to tell process "Adobe Acrobat Reader DC"
	repeat rowCount times
		AST click at {140, 311}
		set currentRow to (currentRow + 1)
	end repeat
end tell

-- Tab back to the starting field
tell application "System Events" to tell process "Adobe Acrobat Reader DC"
	repeat 3 times
		keystroke tab
	end repeat
end tell

set currentRow to 1

-- Iterate over Excel rows
repeat rowCount times
	repeat with currentLetter in columnLetters
		-- Copy value from Excel
		tell application "Microsoft Excel"
			set currentCell to currentLetter & currentRow as string
			set the clipboard to value of cell currentCell as string
		end tell
		-- Paste value into Acrobat and tab to next field
		activate application "Adobe Acrobat Reader DC"
		tell application "System Events" to tell process "Adobe Acrobat Reader DC"
			keystroke "v" using command down
			-- Corrects for issue with keypresses occurring too quickly
			delay 0.1
			keystroke tab
		end tell
	end repeat

	if currentRow is greater than 1 then
		if currentPage is equal to 1 then
			set pagebreakCount to pagebreakCountFirst
			set pagebreakMod to 0
		else if currentRow > pagebreakCountSubsequent then
			set pagebreakCount to pagebreakCountSubsequent
			set pagebreakMod to (pagebreakCountSubsequent - 1)
		else
			set pagebreakCount to false
		end if

		if (pagebreakCount is not false) and ((currentRow mod pagebreakCount) is equal to pagebreakMod) then
			repeat pagebreakExtraTabs times
				tell application "System Events" to tell process "Adobe Acrobat Reader DC"
					keystroke tab
				end tell
			end repeat

			-- Increment page counter to help with determining page breaks more easily
			set currentPage to (currentPage + 1)
		end if
	end if

	-- Two extra tabs to get to next set of fields
	repeat 2 times
		tell application "System Events" to tell process "Adobe Acrobat Reader DC"
			keystroke tab
		end tell
	end repeat
	set currentRow to (currentRow + 1)
end repeat

-- From http://www.cubemg.com/how-to-get-the-number-of-rows-inan-excel-spreadsheet-with-applescript/
to getRowCount()
	tell application "Microsoft Excel"
		tell active sheet
			tell used range
				set rc to count of rows
			end tell
			return rc
		end tell
	end tell
end getRowCount

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.