简体   繁体   English

使用Powershell在MS Word中编辑文本表单域

[英]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. 我正在尝试编写一个Powershell脚本来编辑Microsoft Office Word 2007中的文本表单字段。它应该通过我之前配置的书签找到一个表单字段并在其中写入文本。 The default text I wrote into it for test purposes is "Something". 我为测试目的写入的默认文本是“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. Word仍显示我之前手动插入的字符串。 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. PS:它也不适用于MS Word 2016。

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". 如果您尝试编写替换VBA中书签的文本(例如),您可能会收到错误6028 - “范围无法删除”。

I don't know Powershell well enough to do this without checking, but the equivalent VBA would be 我不知道Powershell在没有检查的情况下做得好,但等效的VBA会是

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

so I would guess the powershell is something like 所以我猜想powershell是这样的

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM