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

问题描述 投票:0回答:1

我正在寻找一种通过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)
powershell word-vba
1个回答
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。您可以在上面链接的页面上找到指向这些枚举的链接。

© www.soinside.com 2019 - 2024. All rights reserved.