缩小范围以添加超链接

huangapple go评论49阅读模式
英文:

Narrowing the range to add Hyperlinks

问题

我提取了包含类似于23/25的模式的文档句子。使用正则表达式完成。

问题是:当在使用正则表达式提取的句子中找到特定单词时,我想要添加到这个23/25的超链接内容会发生变化。

我找到的添加超链接的代码不允许我将范围缩小到找到的句子,并要求我使用ActiveDocument.range,因此是整个文档内容。

使用下面的代码,所有的23/25都将以相同的超链接结束。

是否有一种方法可以将范围设置/缩小到使用正则表达式找到的句子?

我知道下面的代码肯定写得不正确,我在这里挣扎。提前感谢您的帮助。

Set objRegex = New RegExp
With objRegex
   .Pattern = "(\d{2}/\d{2})([a-zA-Zé /'/., ]{2,250})"
   .Global = True
   .IgnoreCase = True
Set matches = .Execute(Txte)
For Each fnd In matches
a = fnd.SubMatches.Count
For i = 0 To a - 1
    If InStr(fnd, "cdtional word") Then
        resul = fnd.SubMatches.Item(1)
Set Rng = ActiveDocument.Range{resul}
With Rng.Find
   Do While .Execute(findText:=resul, Forward:=False) = True
       Rng.MoveEndUntil (" ")
       ActiveDocument.Hyperlinks.Add _
       Anchor:=Rng, _
       Address:="https://bla.org/" & resul
       Rng.Collapse wdCollapseStart
   Loop
Next

(结束标签)


<details>
<summary>英文:</summary>

I extract sentences of a document containing a pattern resembling to 23/25.
Done with reg. expressions.
The issue : having the content of the hyperlink I want to add to this 23/25 change when a specific word is found in the sentence extracted with the regexes.

The code I found to add a hyperlink doesn&#39;t let me narrow the range to the very sentence found and has me use the Activedocument.range, so the entire doc content. 
With the code hereunder, all occurrences of say 23/25 will end up with the same hyperlink.

Is there a way to set/narrow the range specifically to the sentence found with the regexes?

I know the code hereunder is definitely not properly written, I&#39;m struggling here. Thanks for your kind help in advance.

    Set objRegex = New RegExp
    With objRegex
       .Pattern = &quot;(\d{2}/\d{2})([a-zA-Z&#233; /&#39;/., ]{2,250})&quot;
       .Global = True
       .IgnoreCase = True
    Set matches = .Execute(Txte)
    For Each fnd In matches
    a = fnd.SubMatches.Count
    For i = 0 To a - 1
        If InStr(fnd, &quot;cdtional word&quot;) Then
            resul = fnd.SubMatches.Item(1)
    Set Rng = ActiveDocument.Range{resul}
    With Rng.Find
       Do While .Execute(findText:=resul, Forward:=False) = True
           Rng.MoveEndUntil (&quot; &quot;)
           ActiveDocument.Hyperlinks.Add _
           Anchor:=Rng, _
           Address:=&quot;https://bla.org/&quot; &amp; resul
           Rng.Collapse wdCollapseStart
       Loop`
(closing tags)

</details>


# 答案1
**得分**: 0

您的代码不完整,请修复它。谢谢。我只能使用您提供的内容,并临时处理它作为答案。如果不满足您的需求,请原谅我。

而且我没有用于测试的文本,所以无法进行实际测试。就像这些行一样,我不知道您在做什么:

```vba
            If InStr(fnd, "cdtional word") Then
                resul = fnd.SubMatches.Item(1)

所以我认为代码应该是这样的:

Sub VBA__MSWORD__Narrowing_the_range_to_add_Hyperlinks()
    Dim objRegex As VBScript_RegExp_55.RegExp, matches As VBScript_RegExp_55.MatchCollection, fnd As VBScript_RegExp_55.match
    Dim Txte As String, d As Document, resul As String, a As Long, i As Long, rng As Range
    
    Set d = ActiveDocument
    Txte = d.Content.Text
    
    Set objRegex = New RegExp
    With objRegex
       .Pattern = "(\d{2}/\d{2})([a-zA-Zé /'., ]{2,250})"
       .Global = True
       .IgnoreCase = True
        Set matches = .Execute(Txte)
    End With
    For Each fnd In matches
        a = fnd.SubMatches.Count
        For i = 0 To a - 1
            If InStr(fnd, "cdtional word") Then
                resul = fnd.SubMatches.Item(1)
                Set rng = d.Range
                With rng.Find
                   Do While .Execute(findText:=resul, Forward:=True, Wrap:=wdFindStop) = True
                       rng.MoveEndUntil (" ")
                       rng.Hyperlinks.Add _
                       Anchor:=rng, _
                       Address:="https://bla.org/" & resul
                       rng.Collapse wdCollapseEnd
                       
                       If rng.Next Is Nothing Then Exit Do
                       rng.SetRange rng.Next.Start, d.Content.End
                   Loop
                End With
            End If
        Next i
    Next fnd
End Sub

您应该根据自己的实际需求修改我的代码。

英文:

Your code is incomplete, please fix it. Thanks. I can only use what you have given and deal with it temporarily as an answer. If it does not meet your needs, please forgive me.

And I don't have a text for testing, so I can't do the actual testing. As in these lines, I don't know what you are doing:

            If InStr(fnd, &quot;cdtional word&quot;) Then
                resul = fnd.SubMatches.Item(1)

So the code I suppose should be:

Sub VBA__MSWORD__Narrowing_the_range_to_add_Hyperlinks()
    Dim objRegex As VBScript_RegExp_55.RegExp, matches As VBScript_RegExp_55.MatchCollection, fnd As VBScript_RegExp_55.match
    Dim Txte As String, d As Document, resul As String, a As Long, i As Long, rng As Range
    
    Set d = ActiveDocument
    Txte = d.Content.Text
    
    Set objRegex = New RegExp
    With objRegex
       .Pattern = &quot;(\d{2}/\d{2})([a-zA-Z&#233; /&#39;/., ]{2,250})&quot;
       .Global = True
       .IgnoreCase = True
        Set matches = .Execute(Txte)
    End With
    For Each fnd In matches
        a = fnd.SubMatches.Count
        For i = 0 To a - 1
            If InStr(fnd, &quot;cdtional word&quot;) Then
                resul = fnd.SubMatches.Item(1)
            &#39;    Set Rng = ActiveDocument.Range{resul}
                Set rng = d.Range
                With rng.Find
                   &#39;Do While .Execute(findText:=resul, Forward:=False) = True
                   Do While .Execute(findText:=resul, Forward:=True, Wrap:=wdFindStop) = True
                       rng.MoveEndUntil (&quot; &quot;)
&#39;                       ActiveDocument.Hyperlinks.Add _
&#39;                       Anchor:=rng, _
&#39;                       Address:=&quot;https://bla.org/&quot; &amp; resul
&#39;                       rng.Collapse wdCollapseStart

                       Rem Try to use rng instead of ActiveDocument
                       rng.Hyperlinks.Add _
                       Anchor:=rng, _
                       Address:=&quot;https://bla.org/&quot; &amp; resul
                       rng.Collapse wdCollapseEnd
                       
                       If rng.Next Is Nothing Then Exit Do
                       Rem Reset the range to be searched:
                       rng.SetRange rng.Next.Start, d.Content.End
                       
                   Loop
                End With
            End If
        Next i
    Next fnd
End Sub

You should modify my code to apply according to your actual needs.

20230603 Without Find object

No need to use the Find object

Option Explicit
&#39;Private linkDict As New Scripting.Dictionary
Private linkDict As Object
Rem https://stackoverflow.com/questions/76386857/vba-msword-narrowing-the-range-to-add-hyperlinks
Rem Dear Omar: the sample text and result is this : Document 25/23 from company X is to be reviewed. Document 25/23 from Company Z as well. – 
Rem I just need the VBA to 1) look for all sentences containing 25/23 , 2) add 1 hyperlink to 25/23 : if the word &quot;Company X&quot; is in that sentence, the hyperlink has to be Http://docs.org/Startups/25/23. But if the word &quot;Company Z&quot; is in that sentence, then the hyperlink has to be Https://docs.org/ngos/25/23 instead. That is all I need really – 

Rem All string comparisons are case-sensitive
Sub VBA_MSWORD_Narrowing_the_range_to_add_Hyperlinks()
    Dim objRegex As VBScript_RegExp_55.RegExp, matches As VBScript_RegExp_55.MatchCollection, fnd As VBScript_RegExp_55.match
    Dim Txte As String, d As Document, resul As String, a As Long, i As Long, rng As Range, ur As UndoRecord, s As Long
    Set ur = Word.Application.UndoRecord
    ur.StartCustomRecord &quot;VBA_MSWORD_Narrowing_the_range_to_add_Hyperlinks&quot;
    
    Set d = ActiveDocument
    Txte = d.Content.Text
    Set rng = d.Range
    
    Set objRegex = New RegExp &#39;Set regex = CreateObject(&quot;VBScript.RegExp&quot;)
Research:
    With objRegex
&#39;       .Pattern = &quot;(\d{2}/\d{2})([a-zA-Z&#233; /&#39;/., ]{2,250})&quot;
       .Pattern = &quot;(\d{2}/\d{2})([a-zA-Z&#233; /&#39;/., ]{2,250})(Company [A-Z])&quot;
       .Global = True
       .IgnoreCase = True
       &#39;.MultiLine=False &#39;default
       Set matches = .Execute(Txte)
    End With
    For Each fnd In matches
        a = fnd.SubMatches.Count
        For i = 0 To a - 1
&#39;            If InStr(fnd, &quot;Company &quot;) Then &#39; this can be omitted because regex is already applying to
                resul = fnd.SubMatches.Item(2)
                With rng
                    .SetRange fnd.FirstIndex + s, fnd.FirstIndex + s + VBA.Len(fnd.SubMatches.Item(0))
                    &#39;.Select &#39;just for test watching only
                       .Hyperlinks.Add _
                       Anchor:=rng, _
                       Address:=GetLink(resul)
                       &#39;rng.Collapse wdCollapseEnd

                       &#39;If rng.Next Is Nothing Then Exit Sub to end this procedure
                       If rng.Next Is Nothing Then
                            ur.EndCustomRecord
                            Exit Sub
                       End If
                       Rem Reset the range to be searched:
                       s = rng.Next.Start
                       rng.SetRange s, d.Content.End
                       
                       Txte = rng.Text
                       GoTo Research
                End With
&#39;            End If
        Next i
    Next fnd
    ur.EndCustomRecord
End Sub

Property Get GetLink(company As String) As String
    &#39;If linkDict.Count = 0 Then
    If linkDict Is Nothing Then
        Set linkDict = CreateObject(&quot;Scripting.Dictionary&quot;)
        With linkDict
            .Add &quot;Company X&quot;, &quot;http://docs.org/Startups/25/23&quot; &#39; &quot;http&quot;? did you lost the &quot;s&quot; ?
            .Add &quot;Company Z&quot;, &quot;https://docs.org/ngos/25/23&quot;
        End With
    End If
    GetLink = linkDict(company)
End Property

缩小范围以添加超链接

Is this what you really want? If there are other relevant details you did not or forgot to mention, you should try to make adjustments yourself. I should have done already my best to fulfill what you said to me.

huangapple
  • 本文由 发表于 2023年6月2日 10:54:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/76386857.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定