I am trying to increase the level of automation within my day-to-day work, part of which involves adding a line to the end of a table within a report that contains largely the same information, with a few cells changed (new dates).
I have a little experience with VB and C , but I am very much an amateur when it comes to PowerShell, which seems to be the go-to for task automation.
I have a couple of PowerShell scripts that search through the body of the report and change text, but the last part of the report is a record, and needs appending as opposed to amending.
How would I go about this?
I have tried mangling a few bits of PowerShell code I've found online, to no avail. I have gotten as far as selecting a row in the correct table, but I have no idea how I might then select the last row, copy this and insert it beneath as a new row at the bottom of the table:
$objWord = New-Object -ComObject word.application
$objWord.Visible = $True
$objWord.Documents.Open("FILEPATH")
$FindText = "KEYTEXT"
$objWord.Selection.Find.Execute($FindText)
$objWord.Selection.SelectRow()
CodePudding user response:
Here's a lengthy example with explanations that does what you're looking for:
# open document
$objWord = New-Object -ComObject word.application
$objWord.Visible = $True
$doc = $objWord.Documents.Open("C:\temp\temp.docx")
# search for row
$FindText = "Value2"
$result = $objWord.Selection.Find.Execute($FindText)
$objWord.Selection.SelectRow()
# copy the ranges from searched row
$table = $objWord.Selection.Tables[1]
$copiedCells = $objWord.Selection.Cells | select columnindex,rowindex
# add row at the end of table
$table.Rows[$table.Rows.Count].Select()
$objWord.Selection.InsertRowsBelow(1)
# insert copied text into each column of last row
foreach ($cell in $copiedCells) {
# copy value from cell in copied row
$copiedText = $table.Cell($cell.rowindex, $cell.columnindex).Range.Text
# remove last 2 characters (paragraph and end-of-cell)
$TrimmedText = $copiedText.Remove($copiedText.Length - 2)
# set value for cell in last row
$table.Cell($table.Rows.Count,$cell.columnindex).Range.Text = $TrimmedText
}