Replace Word text using Interop

Hello all,

Here’s the update on that code I was writing before. The problem above wasn’t the only road block I ran into so I decided to figure it all out before posting so I wasn’t just talking to myself. :smiley:

I will eventually make this into a .dyf so it can be used for other documents and makes more sense to people who don’t know how to use it. You’ll have to see if I make it public or not, still deciding. :stuck_out_tongue:

A special thanks to https://gist.github.com/ejstembler/1049552 and https://github.com/allevaton because I would’ve been completely lost in writing this without them. Also thanks to @jacob.small for help in figuring out a gameplan and guidance!

Last thing, if there’s any advice or edits you’d like to write as a reply, I’m more than happy to hear it!
Thanks!

# Written by Lynn Quagliato, https://forum.dynamobim.com/u/quagliatol/summary
# Some code taken from https://gist.github.com/ejstembler/1049552
# Made with help from https://github.com/allevaton

# Imports

import clr
import sys
import System

clr.AddReference("Microsoft.Office.Interop.Word")
import Microsoft.Office.Interop.Word as Word

# Code

def doc_replace_text(source_filename, tokens, values, destination_filename):
	
	missing = System.Type.Missing
	replaceAll = Word.WdReplace.wdReplaceAll
	
	word_application = Word.ApplicationClass()
	word_application.visible = False
	
	document = word_application.Documents.Open(source_filename, missing, True)
	
	for i in range(len(tokens)):
		for r in document.StoryRanges:
			r.Find.Execute(
			tokens[i], # search text
			missing, # match case
			missing, # match whole word
			missing, # match wildcards
			missing, # match sounds like
			missing, # match all word forms
			True, # forward?
			Word.WdFindWrap.wdFindContinue, # wrap enum
			missing, # format?
			values[i], # replace with
			replaceAll, # replace enum
			missing, # match Kashida (arabic letters)
			missing, # diatrics?
			missing, # match other Arabic letters
			missing # support right to left
			)
	
	document.SaveAs(destination_filename)
	document.Close()
	document = None
	
	word_application.Quit()
	word_application = None

# Inputs and function

file_name = IN[0]
search_terms = IN[1]
replace_terms = IN[2]
destination_name = IN[3]

doc_replace_text(file_name, search_terms, replace_terms, destination_name)

# Assign your output to the OUT variable.

OUT = 1

PS. Yes, output is 1 no matter what because I’m still learning and working on this. lol

6 Likes