Automate a Grep Applescript to Word Document - ms-word

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!

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

Related

How to pass argument for the apple script

I have following script :)
property word_docs : {"org.openxmlformats.wordprocessingml.document", "com.microsoft.word.doc"}
property default_path : (path to desktop) as alias
property Delim : {".docx", ".doc"}
property PDF : ".pdf"
set outPDF to {}
set selected_files to (choose file of type word_docs default location default_path with multiple selections allowed without invisibles and showing package contents)
set {TID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, Delim}
repeat with afile in selected_files
copy item 1 of text items of (afile as text) & PDF to the end of outPDF
end repeat
set AppleScript's text item delimiters to TID
tell application id "com.microsoft.Word"
activate
repeat with i from 1 to count of selected_files
open (item i of selected_files)
set theOutputPath to (item 1 of outPDF)
-- close access (open for access exportDocument)
tell active document
save as it file name theOutputPath file format format PDF
close saving no
end tell
end repeat
end tell
return
That helps me convert doc & docx files -> pdf, but it is too interactive.
And I have idea to run this script via terminal and i want to pass file path or directory as argument
for example:
$ script /Users/test/dest_dir/ /Users/test/out_dir/
will produce all pdf files into out_dir.
I saw this library also but it converts only docx files:
https://pypi.org/project/docx2pdf/
Is there anyone here who can help me rewrite this script .. I don't understand this language at all. or maybe someone will point to the finished tool. I need to do this on the mac os operating system.
see http://hints.macworld.com/article.php?story=20050523140439734
argv is an array of arguments in string format
on run argv
return item 1 of argv

Applescript for inserting hyperlink into MSWord comment

I'm trying to add a hyperlink object inside a Word comment.
To create a new comment in the active document I'm using this piece of script:
tell application "Microsoft Word"
set tempString to "lorem ipsum"
make new Word comment at selection with properties {comment text:tempString}
end tell
but now I'm not able to get a reference to the new created comment for use it with the command "make new hyperlink object".
Thanks for any suggestions.
Riccardo
I don't think you can work with the object returned by make new Word comment (at least not in this case), and you have to insert a unique, findable string then iterate through the comments:
tell application "Microsoft Word"
-- insert a unique string
set tempString to (ASCII character 127)
set theComments to the Word comments of the active document
repeat with theComment in theComments
if the content of the comment text of theComment = tempString then
set theRange to the comment text of theComment
-- you do not have to "set theHyperlink". "make new" is enough
set theHyperlink to make new hyperlink object at theRange with properties {text range:theRange, hyperlink address:"http://www.google.com", text to display:"HERE", screen tip:"click to search Google"}
insert text "You can search the web " at theRange
exit repeat
end if
end repeat
end tell
(edited to insert some text before the Hyperlink. If you want to insert text after the hyperlink, you can also use 'insert text "the text" at end of theRange.).
So for adding text, it was enough to use "the obvious" after all.
[
For anyone else finding this Answer. The basic problem with working with Word ranges in Applescript is that every attempt to redefine a range in the Comments story results in a range that is in the main document story. OK, I may not have tried every possible method, but e.g., collapsing the range, moving the start of range and so on cause that problem. In the past, I have noticed that with other story ranges as well, but have not investigated as far as this.
Also, I suspect that the reason why you cannot set a range to the Word comment that you just created is because the properties of the Comment specify a range object of some kind that I think is a temporary object that may be destroyed immediately after creation. SO trying to reference the object that you just created just doesn't work.
This part of the Answer is modified...
Finally, the only other way I found to populate a Comment with "rich content" was to insert the content in a document at a known place, then copy its formatted text to the comment, e.g. if the "known place is the selection, you can set the content of theComment via
set the formatted text of the comment text of theComment to the formatted text of the text object of the selection
If you are using a version of Word that supports VBA as well as Applescript, I don't really see any technical reason why you shouldn't invoke VBA to do some of these trickier things, even if you need the main code to be Applescript.
]
Finally I got a solution here:
https://discussions.apple.com/message/24628799#24628799
that allowed me to insert the hyperlink in reference with part of the comment text, with the following lines, if somebody in the future will search for the same:
tell application "Microsoft Word"
set wc to make new Word comment at end of document 1 with properties {comment text:"some text"}
set ct to comment text of wc
set lastChar to last character of ct
make new hyperlink object at end of document 1 with properties {hyperlink address:"http://www.example.com", text object:lastChar}
end tell

How to do search and replace involving fields in Microsoft Word?

I have a Word document with fields of the reference variety, which occur in the form "[field].[field]"--in other words, there's a period between the two fields. I want to globally replace this with a space.
Word offers the ^d special character to search for fields, but for some reason the query "^d.^d" does not find anything. However, ".^d" does. Now comes the problem, however--what do I specify as the replacement text in order to retain the field code? If using regular expressions, I could use a "Find What Expression" such as \1, but with regexp ("wild card") mode the ^d is not permitted.
I guess I could write a macro...
I would like to add to Bibadia's solution.
An example of an index entry field; we want to change a name we misspelled.
Make sure hidden formatting is displayed (toggle with SHIFT+CTRL+F8).
Make sure wildcards option is not selected. To search for fields, use the opening and closing field braces code (optionally use ^w for spaces, as Bibadia suggested):^19 XE "Deo, John" ^21
Replace won't recognize field braces character, but will allow to insert the clipboard's content. ;). To do that, insert in text the correct entry. CTRL+F9 to insert field and type:XE "Doe, John"
Select the field above and copy
Use ^c in the replace box
Hit Replace All
Ta-da!
It's usually better to go the macro route when finding fields because, as you say, the find algorithm that Word uses doesn't work the way you might hope with fields.
But if you know exactly what the fields contain, you can specify a search pattern that will probably work (however not in wildcard mode).
For example, if you want to look for figure number field pairs such as
{ STYLEREF 1 \s }.{ SEQ Figure \* ARABIC \s 1 }
(which would typically be the same set of fields everywhere in the document)
If you only really need to look for the following:
{ STYLEREF 1 \s }.<any field>
you could ensure that field codes are displayed and search for
^d STYLEREF 1 \s ^21.^d
or
^19 STYLEREF 1 \s ^21.^19
If you need to be more precise, you can spell out the second field as well.
"^d" only works for finding the field beginning, not the field end.
It's a shame that ^w wants to find at least 1 whitespace character because otherwise it would be more robust to look for
^19^wSTYLEREF^w1^w\s^w^21.^19
Perhaps someone else knows how to work around that without using wildcards?
Torzaburo,
I suggest that you do this using a macro. You can start by recording the macro, and later refining your processing steps within the macro.
First turn on the hidden characters by navigating to Home > Paragraph > toggle the show/hide Paragraph symbol. Also, select all and toggle the field codes on (right-click and select "Toggle Field Codes".
Open a new blank Word doc in addition to the one you have open. You will use this later. Start the macro recording and find the field using the "^d" (field code) as you said.
When the field is found, copy only the field text within the brackets, and not the full field reference. While the macro is still recording, ALT + TAB to the new blank document and paste the field code in as plain text.
At this point, do the necessary find & replace processing to the field codes. Highlight the processed field codes, copy, ALT + TAB back to the original document, and paste back between the { } brackets.
Stop the macro recording. Add any further custom processing to the macro VBA.
Select-All and re-toggle the field codes. Update the field codes.
You don't need a macro. Just toggle all field codes on by using Alt+F9. Then do a find and replace for what you want to change. Once the replacement is complete, use Alt+F9 again to toggle the field codes back off.
Disclaimer: I didn't originate this solution, but it's clean and elegant and I thought it should be included here:
(Adapted from Search & Replace Field Codes in Word):
Create or find a single instance of the field you want to convert text to
Toggle Field Codes visible (AltF9)
Copy the code for the field you want to use to the Clipboard (highlight and CtrlC)
Open the Replace dialog box (CtrlH), insert the text you want to replace in the Find What box and then enter ^c in the Replace With box.
This will replace your text with the contents of the Clipboard, turning it into the field code you copied in step 3. It also copies formatting information (font, color, etc.), to control how the field will appear when hidden. (Caveat: I've tested this with Word 2003 under Windows 7 only.)
Coming in late on this, probably way too late for Beth (sorry Beth). And this may not be quite what Beth was looking for. But for anyone interested ...
It sounds like Beth may have created captions throughout the document using INSERT CAPTION (hence the presence of field codes). This means these captions will have been (automatically) created in CAPTION style.
To globally replace the separator "." with " " (space) in such captions, take two steps:
[1] Go to REFERENCES | INSERT CAPTION, then click on NUMBERING and replace the SEPARATOR "." with "EM-DASH". This will replace all separators in captions for the selected label in the CAPTION Window. If you have other labels in use in the document (e.g. FIGURE), select the other labels one by one and repeat this process.
[2] Do a find/replace searching for special character "em-dash" (^+) in style CAPTION, replacing with " ". Click REPLACE ALL.
Voila!
NOTE: This presumes that em-dash does not appear in the caption text anywhere. If it does, then you'll need to do a pre- and post- "fiddle" to ensure these em-dashes are not touched by the global replace above.
The "pre-fiddle" is to do a global find/replace across captions, replacing the em-dash ("^+") with some other string (e.g. "EM-DASH") that doesn't ever occur in any caption's text. Then you do the separator change as described above. Finally, the "post-fiddle" is to restore the em-dashes that were in the captions, by doing a global replace of the string "EM-DASH" with the actual em-dash character "^+".

What is the correct syntax for save as active document in Word using Applescript?

I am going nuts here. I have tried countless permutations/variations of "save as active document file format PDF" but none seem to work. I get AppleScript errors with all of them.
So can anyone tell me:
What is the exact syntax to save the active document as a PDF file in AppleScript, using Word?
It seems that there is no coherence whatsoever in the Office for Mac scripting, as I have this working for Excel and PowerPoint and even there the syntax is different:
excel
save active workbook in 'MyFile.pdf' as PDF file format
PowerPoint
save active presentation in 'MyFile.pdf' as save as PDF
What is the correct syntax for Word?
Thanks!
It seems I found it after all:
set myDoc to "/Users/X/Desktop/test.docx"
set pdfSavePath to "Users:X:Desktop:test.pdf"
tell application "Microsoft Word"
activate
open myDoc
set theActiveDoc to the active document
save as theActiveDoc file format format PDF file name pdfSavePath
end tell
I am no AppleScript expert. I had slashes instead of : as path separators. With : it works
Joris Mans script is pretty nice, but has a flaw. It does not ensure that Word has an active document ready (set theActiveDoc to the active document might return missing value)
I also improved the script to use the Finder selection as input, placing the PDFs into the same place as the word files. I did not test the file types, but word will complain about that.
tell application "Finder"
set input to selection
end tell
tell application id "com.microsoft.Word"
activate
repeat with aFile in input
open aFile
set theOutputPath to ((aFile as text) & ".pdf")
repeat while not (active document is not missing value)
delay 0.5
end repeat
set activeDoc to active document
save as activeDoc file name theOutputPath file format format PDF
close active document saving no
end repeat
end tell

Can I make a macro in n++ that does a search/replace?

I'm new to n++, but I have been most impressed with this tool so far. I've been trying to record a macro that do a search/replace, but the 'search' part seems to have the initial search text from the recording 'hard-coded' in the macro.
What I want is:
Manually locate the cursor at the beginning of the first line of a fixed format code segment, then Macro actions:
move cursor two lines down
move cursor right x characters
mark charters from pos x to x+n
search and replace all occurrences of the selected text with "{p_'selected text'}"
In an more advanced version, I'd like to add some logic to step 4: only execute the replace part if the # of occurrences are > 1 (e.g. by first adding a count statement, but I'm not sure how to obtain the returned count # from the dialog box)
Is this possible?
While I'm a big fan of Notepad++, this sounds like something I would accomplish with AutoHotKey. You would select the text and copy it to the clipboard. AutoHotKey would read the clipboard, replace the text as you desire, and either replace the clipboard contents, or send it back to your document. Let me know if you would like to go that route.