用超链接替换 ​​Word 文件中所有出现的字符串 [英] Replacing all occurrences of a string in a Word file by an hyperlink

查看:55
本文介绍了用超链接替换 ​​Word 文件中所有出现的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须创建一个 Powershell 脚本来读取 Word 文件 (.docx) 并用超链接替换字符串.到目前为止,基于 这个脚本,我可以很容易地用另一个字符串替换所有出现的字符串.随着 那个脚本,我可以查找一个字符串并用超链接替换它.但是,只会替换第一次出现.

I have to create a Powershell script that reads a Word file (.docx) and replaces strings by hyperlinks. So far, based on this script, I can replace all occurrences of a string by another string easily. With that script, I can look for a string and replace it by an hyperlink. However, only the first occurrence is replaced.

这是我目前对问题的理解:

Here's my understanding of the problem so far :

第一个脚本使用Find接口的Execute函数的ReplaceWithReplace=wdReplaceAll参数.问题是 ReplaceWith 需要一个 String 而不是 Hyperlink 对象.

The first script uses the ReplaceWith and Replace=wdReplaceAll parameters of the Execute function of the Find Interface. The issue is that ReplaceWith expects a String and not an Hyperlink object.

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

The second script doesn't specify those parameters so it only uses the Find.Execute() function to move the start of the Range object to the found string and then insert a link at that position.

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

Since I can't replace all occurrences at once, I'd try to iterate through all matches to insert links at their location. But Find.Execute() only returns a Boolean... Now I'm thinking of maybe redefining the range to exclude the found occurrence and looping until the end of the doc, but this feels complicated.

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

Let's say I've got a Word file with this text :

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

In other words, each of the articles linked here is an index to multiple lists on a topic. Some of the linked articles are themselves lists of lists of lists. This article is also a list of lists.

这是一个简单的脚本,它仅用相对链接替换第一次出现的列表".我试图将所有出现的列表"替换为超链接 $linkPath,但找不到方法.帮助?

Here's a bare bone script that replace only the first occurrence of "lists" by a relative link. I'm trying to replace all occurrences of "lists" to the hyperlink $linkPath, but can't find how. Help ?

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()

参考

推荐答案

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

As with any dataset you have to loop to hit all items in the data set to take action on specific in the dataset. You are not doing this in your code. In MSWord, you need to walk the document. For example I am show code for deletes, but this just as well could be your replace effort.

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

Example: VBA for just delete any hyper link

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 示例

Example PowerShell for delete all hyperlinks

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

Example: PowerShell for delete only image hyperlinks

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()

这篇关于用超链接替换 ​​Word 文件中所有出现的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆