Hi there. I am trying to do a find and replace in MS Word and it seems the best option is to use the Word UI to do this (not ideal I know). However I am having trouble opening the file in Word using the Open Application activity as I cannot work out how to put a variable into the command. The file was created dynamically in a previous step and changes very time I run the Workflow. How can i use a variable as a filename, or even better is there a cleaner way to find and replace words in a Word document that has table and images etc.
automating office using the UI is a nightmare, that is why most rpa tools have a way to work with office using PIA.
In OpenRPA, if you install it on a machine with a supported version of office ( 2010 or higher ) you get access to a bunch for activities under OpenRPA.Office
for working with office.
You can use GetParagraph
and SetParagraph
to update a work document.
There is an example on how to do that here
Ah that is so easy. Regrettably the source document has content in tables, it looks like that function cannot see inside the tables. Is that right? Is there a way around that, other than getting the client to accept a redesigned document or use Excel.
Technically that is possible, but the activities I made for OpenRPA are very basic and do not offer the option of embedding other office types. If you are lucky, there might be some on NuGet (made for UiPath before they forced everyone to reference their assemblies) or you can do it manually using Invoke Code (but I do not have time to give you an example on how to do that right now, sorry).
Thanks Allan I understand.
I managed to find the following Powershell script that does the job nicely based on this Scripting Office with PowerShell: Finding and Replacing Text in Word Documents
$Word = New-Object -ComObject Word.Application
# Specify the path to the specific Word document you want to open
$WordFilePath = "C:\path\to\your\document.docx"
$FindText = "10 Main Street" # <= Find this text
$ReplaceText = "22 Industrial Park Road" # <= Replace it with this text
$MatchCase = $false
$MatchWholeWord = $true
$MatchWildcards = $false
$MatchSoundsLike = $false
$MatchAllWordForms = $false
$Forward = $false
$Wrap = 1
$Format = $false
$Replace = 2
# Open the specific document
$Document = $Word.Documents.Open($WordFilePath)
# Find and replace the text using the variables we just set up
$Document.Content.Find.Execute($FindText, $MatchCase, $MatchWholeWord, $MatchWildcards, $MatchSoundsLike, $MatchAllWordForms, $Forward, $Wrap, $Format, $ReplaceText, $Replace)
# Save and close the document
$Document.Close(-1) # The -1 corresponds to https://docs.microsoft.com/en-us/office/vba/api/word.wdsaveoptions
$Word.Quit()
nice, glad yuu found a solution, and thank you for sharing it,
This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.