Mauritz Mauritz - 3 months ago 24
AppleScript Question

Automate a Grep Applescript to Word Document

I'm using a Mac and I'm preparing accounts for a company. Every payslip which I've made in Microsoft Word has a voucher number. Because a transaction was missed all voucher numbers are wrong so now there are hundreds of wrong payslips. I want to create a script that can find the following GREP (find beginning of paragraph, text:Vch, any character until \r):

^Vch.+\r


and replace it with nothing (thereby deleting the whole sentence).

I was thinking of using Applescript as it can open the document, perform the GREP find (tricky part), save the document and save it as a pdf (all which is needed).

But apparently my knowledge fails me. Commands from the dictionary like create range, execute find, all bring errors.

Somebody experienced in Applescript that could help me devise a script? Any suggestions? It should be something like:

Tell application "Microsoft Word"
tell active document
set myRange to create range start 0 end 0
tell myRange
execute find find "^Vch.+\r" replace with ""
end tell
end tell
end tell


Many thanks!

Answer

There are no special characters to indicate the beginning of a line.

To search at beginning of the paragraph, the script must use return & "some text"

You can use "^p" as paragraph mark, but it doesn't work when you set the match wildcards property to true

To match an entire paragraph, the script must use return & "some text" & return, and the script must use replace with return to delete one paragraph mark instead of two.

Because the first paragraph does not begin with a paragraph mark, the script must use two execute find commands.

The wildcard is *


tell application "Microsoft Word" -- (tested on version 15.25,  Microsoft Office 2016)

    -- check the first  paragraph
    select (characters of paragraph 1 of active document)
    execute find (find object of selection) find text ("Vch*" & return) replace with "" replace replace one wrap find find stop with match wildcards and match case without match forward and find format

    --to search forward toward the end of the document.
    execute find (find object of selection) find text (return & "Vch*" & return) replace with return replace replace all wrap find find continue with match wildcards, match case and match forward without find format

    save active document

    -- export to PDF in the same directory as the active document
    set pdfPath to path of active document & ":" & (get name of active window) & ".pdf"
    set pdfPath to my createFile(pdfPath) -- create an empty file if not exists, the handler return a path of type alias (to avoid grant access issue)
    save as active document file name pdfPath file format format PDF
end tell

on createFile(f)
    do shell script "touch " & quoted form of POSIX path of f
    return f as alias
end createFile
Comments