powershellms-wordbookmarksform-fields

Edit a Text Form Field in MS Word with Powershell


i'm trying to write a Powershell-script that edits Text Form Fields in Microsoft Office Word 2007. It should find a Form Field via the Bookmark I configured before and write a Text into it. The default text I wrote into it for test purposes is "Something". That's what I have so far:

$document = 'D:\Powershell\Test.docx'
$Word = New-Object -Com Word.Application
$Word.Visible = $True
$doc = $word.Documents.Open($document)
$text = "Hello"
$bookmark = "server1"
$doc.Bookmarks.Item($bookmark).Range.Text.Replace("Something", $text)

While it works in the console since the output is:

FORMTEXT Hello

Word still displays the String I inserted manually before. When I type in:

$doc.Bookmarks.Item($bookmark).Range.Text

The output is:

FORMTEXT Something

I already tried:

$Word.ActiveDocument.Reload()
$Word.ActiveDocument.Fields.Update()
$doc.PrintPreview()
$doc.ClosePrintPreview()
$doc.Bookmarks.Item($bookmark).Range.Fields.Update()

But nothing seems to work. Has somebody an idea how to write something in that Text Form Field permanently? Alternatively if that's easier I could use a (rich) Text Content Control (which seem to be newer). Those don't use a bookmark but a tag and title. Thanks for you help in advance . PS:It doesn't work with MS Word 2016 either.


Solution

  • When you have a legacy text form field, the bookmark is really there to identify the field. If you try to write replace the text of the bookmark in VBA (say) you'll probably get Error 6028 - "The range cannot be deleted".

    I don't know Powershell well enough to do this without checking, but the equivalent VBA would be

    doc.FormFields($bookmark).Result = "Something"
    

    so I would guess the powershell is something like

    $doc.FormFields.Item($bookmark).Result = "Something"