我正在尝试整理一个PowerShell
脚本,在整个Word
文档中进行多次查找和替换,包括Headers
,Footers
和任何{{ 1}}可能显示文字。
周围有很多Shape
例子,所以它并不太难,但是有一个知道的错误在VBA中被规避,其解决方案被称为" Peter Hewett' s VBA技巧"。请参阅this example和this one
我试图在VBA
中以类似的方式解决此错误,但它没有按预期工作。 PowerShell
或TextBoxes
中的某些Header
仍被忽略
然而,我注意到,两次运行我的脚本实际上最终会起作用。
对于解决这个问题的任何想法都将不胜感激。
Footer
答案 0 :(得分:0)
我查看了Microsoft文档documentation here,然后我认为以下代码可以执行此操作。
$word = New-Object -ComObject Word.Application
$word.visible=$false
$files = Get-ChildItem "C:\Users\Ali\Desktop\Test" -Filter *.docx
$find="Hello"
$replace="Bye"
$wdHeaderFooterPrimary = 1
$ReplaceAll = 2
$FindContinue = 1
$MatchCase = $false
$MatchWholeWord = $false
$MatchWildcards = $false
$MatchSoundsLike = $false
$MatchAllWordForms = $false
$Forward = $true
$Wrap = $findContinue
$Format = $false
for ($i=0; $i -lt $files.Count; $i++) {
$filename = $files[$i].FullName
$doc = $word.Documents.Open($filename)
ForEach ($StoryRange In $doc.StoryRanges){
$StoryRange.Find.Execute($find,$MatchCase,
$MatchWholeWord,$MatchWildcards,$MatchSoundsLike,
$MatchAllWordForms,$Forward,$Wrap,$Format,
$replace,$ReplaceAll)
While ($StoryRange.find.Found){
$StoryRange.Find.Execute($find,$MatchCase,
$MatchWholeWord,$MatchWildcards,$MatchSoundsLike,
$MatchAllWordForms,$Forward,$Wrap,$Format,
$replace,$ReplaceAll)
}
While (-Not($StoryRange.NextStoryRange -eq $null)){
$StoryRange = $StoryRange.NextStoryRange
$StoryRange.Find.Execute($find,$MatchCase,
$MatchWholeWord,$MatchWildcards,$MatchSoundsLike,
$MatchAllWordForms,$Forward,$Wrap,$Format,
$replace,$ReplaceAll)
While ($StoryRange.find.Found){
$StoryRange.Find.Execute($find,$MatchCase,
$MatchWholeWord,$MatchWildcards,$MatchSoundsLike,
$MatchAllWordForms,$Forward,$Wrap,$Format,
$replace,$ReplaceAll)
}
}
}
#shapes in footers and headers
for ($j=1; $j -le $doc.Sections.Count; $j++) {
$FooterShapesCount = $doc.Sections($j).Footers($wdHeaderFooterPrimary).Shapes.Count
$HeaderShapesCount = $doc.Sections($j).Headers($wdHeaderFooterPrimary).Shapes.Count
for ($i=1; $i -le $FooterShapesCount; $i++) {
$TextRange = $doc.Sections($j).Footers($wdHeaderFooterPrimary).Shapes($i).TextFrame.TextRange
$TextRange.Find.Execute($find,$MatchCase,
$MatchWholeWord,$MatchWildcards,$MatchSoundsLike,
$MatchAllWordForms,$Forward,$Wrap,$Format,
$replace,$ReplaceAll)
}
for ($i=1; $i -le $HeaderShapesCount; $i++) {
$TextRange = $doc.Sections($j).Headers($wdHeaderFooterPrimary).Shapes($i).TextFrame.TextRange
$TextRange.Find.Execute($find,$MatchCase,
$MatchWholeWord,$MatchWildcards,$MatchSoundsLike,
$MatchAllWordForms,$Forward,$Wrap,$Format,
$replace,$ReplaceAll)
}
}
$doc.Save()
$doc.close()
}
$word.quit()