1

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?

macropod
  • 12,757
  • 2
  • 9
  • 21
mzuba
  • 1,226
  • 1
  • 16
  • 33

1 Answers1

1

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()
I_O
  • 4,983
  • 2
  • 2
  • 15
  • Do you know why the assignment is necessary here? – mzuba Jan 10 '23 at 13:16
  • Unfortunately not; I just got lucky after considering that Range is a class in VBA, Text being one of its properties or methods (according to the RDCOMClient's documentation, the difference is *"a little nebulous"*), so I thought it might help to retrieve the Range as an R object to set its property 'Text' later on. – I_O Jan 10 '23 at 13:41
  • btw, package {officer} might also be helpful: https://ardata-fr.github.io/officeverse/officedown-for-word.html – I_O Jan 10 '23 at 22:17