我正在尝试查找并替换word文档。我有2个问题我得到错误Exception calling "Execute" with "15" argument(s): "String parameter too long."
我假设因为我的替换文本超过255个字符。有人可以用另一种方法帮助我让脚本替换超过255个字符吗?
这是代码
$Filename=file1.docx
Function OpenWordDoc($Filename)
{
$Word=NEW-Object –comobject Word.Application
Return $Word.documents.open($Filename)
}
[xml]$xmldata = Get-Content "file.xml"
$Doc=OpenWordDoc -Filename "file1.docx"
Function SearchAWord($Document,$findtext,$replacewithtext)
{
$FindReplace=$Document.ActiveWindow.Selection.Find
$matchCase = $false;
$matchWholeWord = $true;
$matchWildCards = $false;
$matchSoundsLike = $false;
$matchAllWordForms = $false;
$forward = $true;
$format = $false;
$matchKashida = $false;
$matchDiacritics = $false;
$matchAlefHamza = $false;
$matchControl = $false;
$read_only = $false;
$visible = $true;
$replace = 2;
$wrap = 1;
$FindReplace.Execute($findText, $matchCase, $matchWholeWord,`
$matchWildCards, $matchSoundsLike, $matchAllWordForms, $forward, $wrap,`
$format, $replaceWithText, $replace, $matchKashida ,$matchDiacritics,`
$matchAlefHamza, $matchControl) | Out-Null
}
Function SaveAsWordDoc($Document,$FileName)
{
$Document.Saveas([REF] $Filename)
$Document.close()
}
$checkcontent = $xmldata.Benchmark.Group.Rule.check.'check-content'
$description = $xmldata.Benchmark.group.rule.description
SearchAWord –Document $Doc -findtext '<Information derived from discussion>' -replacewithtext $description
SearchAWord –Document $Doc -findtext '<Information derived from content>' -replacewithtext $checkcontent
SaveAsWordDoc –document $Doc –Filename "results.docx"
感谢任何建议。
答案 0 :(得分:2)
我最终修改了我的代码。我在word文档中分配了一些书签,并为这些书签分配了书签变量。所以这段代码会找到我设置的书签,并用我告诉它的内容替换它。
以下是最终结果:
$template = "template.docx"
$wd = New-Object –comobject Word.Application
$doc=$wd.documents.Add($template)
[xml]$xmldata = Get-Content "file.xml"
$newfile="file.docx"
$description = $xmldata.Benchmark.group.rule.description
$checkcontent = $xmldata.Benchmark.Group.Rule.check.'check-content'
#replace Description Bookmark
$objrange = $doc.Bookmarks.Item("Description").Range
$objrange.Text = $description
#replace Check Content Bookmark
$objrange = $doc.Bookmarks.Item("CheckContent").Range
$objrange.Text = $checkcontent
#save and close document
$doc.SaveAs([ref]$newfile)
$doc.Close()
$wd.Quit()