17

I have the following code:

Sub AddSources()
    Dim pubPage As Page
    Dim pubShape As Shape
    Dim hprlink As Hyperlink
    Dim origAddress() As String
    Dim exportFileName As String
    exportFileName = "TestResume"
    Dim linkSource As String
    linkSource = "TestSource2"
    Dim hyperLinkText As TextRange



    For Each pubPage In ActiveDocument.Pages
        For Each pubShape In pubPage.Shapes
            If pubShape.Type = pbTextFrame Then
                For Each hprlink In pubShape.TextFrame.TextRange.Hyperlinks
                    If InStr(hprlink.Address, "http://bleaney.ca") > 0 Then
                        hyperLinkText = hprlink.Range
                        origAddress = Split(hprlink.Address, "?source=")
                        hprlink.Address = origAddress(0) + "?source=" + linkSource
                        hprlink.Range = hyperLinkText
                    End If
                Next hprlink
            End If
        Next pubShape
    Next pubPage
    ThisDocument.ExportAsFixedFormat pbFixedFormatTypePDF, "C:\" + exportFileName + ".pdf"
End Sub

I am getting the "Object variable or With block variable not set (Error 91)" error on the line with hyperLinkText = hprlink.Range. When I debug I can see that hprlink.Range does have a value. Any thoughts what I'm doing wrong?

Vogel612
  • 5,620
  • 5
  • 48
  • 73
GBleaney
  • 2,096
  • 2
  • 22
  • 40
  • 6
    Try writing `Set hyperLinkText = hprlink.Range" – Barranka Dec 19 '13 at 21:46
  • That did it. Thanks! Out of curiosity, why is that Set required? – GBleaney Dec 19 '13 at 21:53
  • TextRange is an object. It has to be instantiated (not possible with TextRange) or made to point ('assigned') to an existing TextRange object, which is done with the Set statement. When executing, the statement was equivalent to trying to assign hprlink.Range to Nothing. – Cor_Blimey Dec 19 '13 at 21:55
  • Related post which is **important to know** while working in VBA - [What does the keyword Set actually do in VBA?](https://stackoverflow.com/q/349613/465053). – RBT Apr 03 '18 at 12:02

1 Answers1

21

As I wrote in my comment, the solution to your problem is to write the following:

Set hyperLinkText = hprlink.Range

Set is needed because TextRange is a class, so hyperLinkText is an object; as such, if you want to assign it, you need to make it point to the actual object that you need.

Jean-François Corbett
  • 37,420
  • 30
  • 139
  • 188
Barranka
  • 20,547
  • 13
  • 65
  • 83