如何从Powershell运行Word宏(替换文本)?

时间:2019-04-26 20:24:19

标签: powershell word-vba

我正在寻找一种通过Powershell替换Word文档中文本的方法。 通过在normal.dot(所有文档)中使用宏,并使用powershell脚本传递查找和替换文本。

Sub Machine()

    Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting
    With Selection.Find
        .Text = $Text
        .Replacement.Text = $ReplaceText
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    Selection.Find.Execute Replace:=wdReplaceAll
End Sub

Powershell脚本

$Desktop = [Environment]::GetFolderPath("Desktop")
$Document = "$Desktop\HL2532-00E.docx"

$Text = "2532-00"
$ReplaceText = "2532-35"

$Word = New-Object -ComObject Word.Application
$Document = $Word.Documents.Open("$Document")
$Word.Run("Machine")
$Document.Save()
$Word.Quit()
$a=[System.Runtime.InteropServices.Marshal]::ReleaseComObject($Word)

1 个答案:

答案 0 :(得分:0)

您没有在宏中定义任何变量。您必须将其更新为以下内容:

Sub Machine(FindText,ReplaceText)

    Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting
    With Selection.Find
        .Text = FindText
        .Replacement.Text = ReplaceText
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    Selection.Find.Execute Replace:=wdReplaceAll
End Sub

然后,当您从PowerShell调用它时,只需在宏名称后添加这些参数:

$Word.Run("Machine",$Text,$ReplaceText)

或者您可以跳过宏,而仅使用Find.Execute()方法(已记录here)在PowerShell中完成所有操作。

$Document = "$home\Desktop\HL2532-00E.docx"

$Text = "2532-00"
$ReplaceText = "2532-35"

$Word = new-object -ComObject Word.Application
$Document = $Word.Documents.Open($Document)
$Find = $Document.Content.Find
$Find.ClearFormatting()|out-null
$Find.Execute($Text, $false, $false, $false, $false, $false, $true, 1, $false, $ReplaceText, 2)
$Document.Save()
$Word.Quit()
$a=[System.Runtime.InteropServices.Marshal]::ReleaseComObject($Word)

Execute方法的语法是:

Execute(FindText, MatchCase, MatchWholeWord, MatchWildcards, MatchSoundsLike, MatchAllWordForms, Forward, Wrap, Format, ReplaceWith, Replace)

其中大多数是$true / $false,其中FindTextReplaceWith是字符串。两个奇数分别是WrapReplace,它们是枚举,其中1 = wdFindContinue和2 = wdReplaceAll。您可以在上面链接的页面上找到这些枚举的链接。