【问题标题】:Replacing all occurrences of a string in a Word file by an hyperlink用超链接替换 ​​Word 文件中所有出现的字符串
【发布时间】:2019-04-20 00:19:53
【问题描述】:

我必须创建一个读取 Word 文件 (.docx) 并用超链接替换字符串的 Powershell 脚本。到目前为止,基于this script,我可以轻松地将所有出现的字符串替换为另一个字符串。使用that script,我可以查找字符串并将其替换为超链接。但是,只会替换第一个匹配项。

到目前为止,这是我对问题的理解:

第一个脚本使用Find接口的Execute函数的ReplaceWith和Replace=wdReplaceAll参数。问题是ReplaceWith 需要一个字符串而不是超链接对象。

第二个脚本没有指定这些参数,所以它只使用Find.Execute() 函数将 Range 对象的开头移动到找到的字符串,然后在该位置插入一个链接。

由于我无法一次替换所有匹配项,我会尝试遍历所有匹配项以在其位置插入链接。但是Find.Execute() 只返回一个布尔值...现在我正在考虑重新定义范围以排除找到的事件并循环到文档末尾,但这感觉很复杂。

假设我有一个包含此文本的 Word 文件:

换句话说,这里链接的每篇文章都是一个索引 一个主题的多个列表。一些链接的文章是他们自己 列表列表列表。这篇文章也是一个列表。

这是一个简单的脚本,它只用相对链接替换第一次出现的“列表”。我正在尝试将所有出现的“列表”替换为超链接 $linkPath,但找不到方法。帮忙?

Add-Type -AssemblyName "Microsoft.Office.Interop.Word"
$wdunits = "Microsoft.Office.Interop.Word.wdunits" -as [type]
$objWord = New-Object -ComObject Word.Application  
$objWord.Visible = $false

# Text to find and replace by a link
$findText = "lists"
# Link to file
$linkPath = ".\Untitled.png"
# Source Word (2007+) file
$objDoc = $objWord.Documents.Open([FILE TO READ FROM])
# Resulting file
$saveAs = [FILE TO SAVE TO]
# Set Range to all document content
$range = $objDoc.Content
$range.movestart($wdunits::wdword,$range.start) | Out-Null

# Execute params
$matchCase = $false
$matchWholeWord = $true
$matchWildcards = $false
$matchSoundsLike = $false
$matchAllWordForms = $false
$forward = $true 
$wrap = 1
$format = $False
$wdReplaceNone = 0 
$wdFindContinue = 1
$wdReplaceAll = 2

# $wordFound is true is $findText is found in $range. 
# $range.find.execute modifies the start of the range 
$wordFound = $range.find.execute($findText,$matchCase,`
             $matchWholeWord,$matchWildCards,$matchSoundsLike,`
             $matchAllWordForms,$forward,$wrap)

if($wordFound){
        $objDoc.Hyperlinks.Add($range,$linkPath,$null,$null,$findText) | Out-Null
}
$objDoc.SaveAs($saveAs)
$objDoc.Close()
$objWord.Quit()
$rc = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($objWord)
[gc]::Collect()
[gc]::WaitForPendingFinalizers()

参考

【问题讨论】:

    标签: vba powershell ms-word


    【解决方案1】:

    与任何数据集一样,您必须循环点击数据集中的所有项目才能对数据集中的特定项目采取行动。您没有在代码中执行此操作。在 MSWord 中,您需要遍历文档。例如,我正在显示删除代码,但这也可能是您的替换工作。

    示例:VBA 用于删除任何超链接

    Sub RemoveHyperlinksInDoc()
        ' You need to delete collection members starting from the end going backwards
        With ActiveDocument
            For i = .Hyperlinks.Count To 1 Step -1
                .Hyperlinks(i).Delete
            Next
        End With
    End Sub
    

    删除所有超链接的示例 PowerShell

    Param
    (
        [string]$Document = $Word.Documents.Open((Read-Host -Prompt 'Enter the full path to the Word document'))
    )
    
    $Word = New-Object -ComObject Word.application
    $Hyperlinks = @($Document.Hyperlinks)  
    $hyperlinks | ForEach { $_.Delete() }
    $document.save()
    $document.Close()
    $word.quit()
    

    示例:PowerShell 仅用于删除图像超链接

    Param
    (
        [string]$Document = $Word.Documents.Open((Read-Host -Prompt 'Enter the full path to the Word document'))
    )
    
    $Word = New-Object -ComObject Word.application
    $Hyperlinks = @($Document.Hyperlinks) 
    $Hyperlinks | ForEach {
                             If ($_.Shape) {$_.Delete()}
                             Else {$_.Name;Write-Warning -Message 'Hyperlink is not a graphic and will not be removed'}
                          }
    $Document.save()
    $Document.Close()
    $Word.quit()
    

    【讨论】:

    • 是的,我几乎认为,由于我无法一次替换所有匹配项,因此我必须遍历所有需要替换的匹配项。困难的部分是我用链接替换单词。我确实找到了一个解决方案,其中涉及计算出现次数并使用 find.execute 移动范围。我会尽快发布,感谢您的帮助。
    • @TheTardis «我几乎是这么想的,因为我不能一次替换所有出现的地方»。如果您将替换超链接(不仅仅是 url)放入剪贴板,则可以使用 Word 的查找/替换功能,以 ^c 作为替换表达式。
    • @macropod 这是一个很好的建议,我更接近我最初的想法。但是,我找不到如何在剪贴板中放置链接。如果我在运行脚本之前手动将链接从 Word 复制到剪贴板,它会完美粘贴。如何通过 VBA 创建链接并将其添加到剪贴板?我不认为我可以使用 Hyperlinks.add 因为它要求锚点...
    • @TheTardis 例如,您可以以编程方式在文档中创建超链接,然后将其从那里复制或剪切到剪贴板。
    猜你喜欢
    • 2016-08-01
    • 2017-10-15
    • 2019-03-22
    • 2016-12-26
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-05
    相关资源
    最近更新 更多