R RDCOMClient 在 Word Doc 中查找和替换

问题描述

我正在尝试自动化替换 Word 报告模板中的某些值的过程。我想找到替换某些值,下面是我尝试过但不起作用的一些代码

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.

解决方法

我找到了以下解决方案:

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://docs.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()