Using RDCOMClient, we can directly replace values in Excel cells, e.g.
range <- sheet$Range('A1')
range[['Value']] <- 1.2
In Word, Texts can be retrieved from the Text
property of a range object, e.g.
word.doc[['Tables']][[1]]$Cell(2, 2)[['Range']][['Text']]
# "12/28/2022\r\a"
But while the Documentation of the range object says that the Text
property can be used to retrieve or set the text of the range, this does not work in RDCOMClient:
word.doc[['Tables']][[1]]$Cell(2, 2)[['Range']][['Text']] <- "test"
# Error in word.doc[["Tables"]][[1]]$Cell(2, 2)[["Range"]][["Text"]] <- "test" :
target of assignment expands to non-language object
Is there a better way to edit the content of a cell or any other range/selection in Word?
If there is no way to do that, would selecting and Selection()$TypeText() or SearchReplace in the Range be more advisable?
It should work when you first get the Range object (from Word's viewpoint) and then set its Text property, e. g.:
library("RDCOMClient")
app <- COMCreate("Word.Application")
doc <- app$Documents()$Open('path_to_your_file.docx'))
## get the VBA object first:
the_range <- doc[['Tables']][[1]]$Cell(2, 2)[['Range']]
## assign its Text property:
the_range[['Text']] = "No cell is an island\n
Entire of itself;\n
Every cell needs a piece of content,\n
A part of the main."
doc$Save()