vbscript:用超链接替换activedocument中的文本

时间:2013-02-15 13:05:46

标签: regex vbscript hyperlink

从一份新工作开始,我必须完成我的前任留下的大量文件。它们是MS Word文件,包含数百项专利的信息。我想用一个可点击的超链接替换所有专利号,而不是复制/粘贴在线表格中的每一个专利号。我想这应该用vbscript完成(我不习惯使用MS Office)。

我到目前为止:

<obsolete>

这对我不起作用: 1.我(可能)需要添加一些东西来循环遍历ActiveDocument 2. replace-function可能需要一个字符串而不是参数的对象 - 在vbscript中是否有__toString()?

THX!

更新: 我有部分工作(正则表达式和查找匹配) - 现在,如果我只能得到超链接的超链接... ...

Sub HyperlinkPatentNumbers()
'
' HyperlinkPatentNumbers Macro
'

Dim objRegExp, Matches, match, myRange

Set myRange = ActiveDocument.Content

Set objRegExp = CreateObject("VBScript.RegExp")
With objRegExp
    .Global = True
    .IgnoreCase = False
    .Pattern = "(WO|EP|US)([0-9]*)(A1|A2|B1|B2)"
End With

Set Matches = objRegExp.Execute(myRange)

If Matches.Count >= 1 Then
    For Each match In Matches
        ActiveDocument.Hyperlinks.Add Anchor:=objRegExp.match, Address:="http://worldwide.espacenet.com/publicationDetails/biblio?DB=EPODOC&adjacent=true&locale=en_EP&CC=$1&NR=$2&KC=$3"
    Next
End If

Set Matches = Nothing
Set objRegExp = Nothing

End Sub

2 个答案:

答案 0 :(得分:0)

这是VBA还是VBScript?在VBScript中,您不能声明类似Dim newText As hyperLink的类型,但每个变量都是变体,因此:Dim newText仅此而已。

objRegEx.Replace返回带有替换的字符串,需要传递两个参数:原始字符串和要用以下代码替换模式的文本:

Set objRegEx = CreateObject("VBScript.RegExp")
objRegEx.Global = True
objRegEx.IgnoreCase = False
objRegEx.Pattern = "^(WO|EP|US)([0-9]*)(A1|A2|B1|B2)$"

' assuming plainText contains the text you want to create the hyperlink for
strName = objRegEx.Replace(plainText, "$1$2$3")
strAddress = objRegex.Replace(plainText, "http://worldwide.espacenet.com/publicationDetails/biblio?DB=EPODOC&adjacent=true&locale=en_EP&CC=$1&NR=$2&KC=$3"

现在,您可以使用strNamestrAddress创建超链接。
专业提示:您可以使用objRegEx.Test(plainText)查看正则表达式是否与早期错误处理相匹配。

答案 1 :(得分:0)

问题解决了:

Sub addHyperlinkToNumbers()

Dim objRegExp As Object
Dim matchRange As Range
Dim Matches
Dim match

Set objRegExp = CreateObject("VBScript.RegExp")

With objRegExp
    .Global = True
    .IgnoreCase = False
    .Pattern = "(WO|EP|US|FR|DE|GB|NL)([0-9]+)(A1|A2|A3|A4|B1|B2|B3|B4)"
End With

Set Matches = objRegExp.Execute(ActiveDocument.Content)

For Each match In Matches
    'This doesn't work, because of the WYSIWYG-model of MS Word:
    'Set matchRange = ActiveDocument.Range(match.FirstIndex, match.FirstIndex + Len(match.Value))

    Set matchRange = ActiveDocument.Content
    With matchRange.Find
        .Text = match.Value
        .MatchWholeWord = True
        .MatchCase = True
        .Wrap = wdFindStop
        .Execute
    End With

    ActiveDocument.Hyperlinks.Add Anchor:=matchRange, _
        Address:="http://worldwide.espacenet.com/publicationDetails/biblio?DB=EPODOC&adjacent=true&locale=en_EP&CC=" _
        & match.Submatches(0) & "&NR=" & match.Submatches(1) & "&KC=" & match.Submatches(2)

Next

MsgBox "Hyperlink added to " & Matches.Count & " patent numbers"

Set objRegExp = Nothing
Set matchRange = Nothing
Set Matches = Nothing
Set match = Nothing

End Sub