rreplacefindrdcomclient

R RDCOMClient find and replace in Word Doc


I'm trying to automate a process that replaces some values from a Word report template. I want to find a replace certain values and below is some code that I've tried but is not working

enter image description here

library(RDCOMClient)
wordApp <- COMCreate("Word.Application")

wordApp[["Visible"]] <- TRUE

newfile <- "~/test_updated_Test.docx"

doc <- wordApp[["Documents"]]$Open(normalizePath(newfile))

print(doc$range()$text())

[1] "Test 123 test\r"

# this does not work
x <- wordApp$ActiveDocument()$Content()

x$Find("Test 123 test",  "test7")

<checkErrorInfo> 80020003 
No support for InterfaceSupportsErrorInfo
checkErrorInfo -2147352573
Error: Member not found.

# this does not work either 
wordApp$ActiveDocument()$Content()$Find("Test 123 test",  "test7")
<checkErrorInfo> 80020003 
No support for InterfaceSupportsErrorInfo
checkErrorInfo -2147352573
Error: Member not found.

Solution

  • I found the following solution :

    library(RDCOMClient)
    library(DescTools)
    
    move_To_Beginning_Doc <- function(doc_Selection)
    {
      doc_Selection$HomeKey(Unit = wdConst$wdStory)
    }
    
    wordApp <- COMCreate("Word.Application")
    wordApp[["Visible"]] <- TRUE
    path_Original_Docx <- "C:/Users/xxx/original_document.docx"
    path_Modified_Docx <- "C:/Users/xxx/modified_document.docx"
    doc <- wordApp[["Documents"]]$Open(normalizePath(path_Original_Docx))
    doc_Selection <- wordApp$Selection()
    move_To_Beginning_Doc(doc_Selection)
    
    # Replace = 2, Replace all occurrences.
    # Replace = 0, Replace no occurrences.
    # Replace = 1, Replace the first occurrence encountered.
    # See https://learn.microsoft.com/en-us/office/vba/api/word.find.execute for the parameters of "Execute"
    doc_Selection$Find()$Execute(FindText = "Apple",
                                 Replace = 2,
                                 ReplaceWith = "DiscountMod")
    
    doc$SaveAs(path_Modified_Docx)
    wordApp$quit()