Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How Do I Automate Adding Hyperlinks to a Word Document? 2

Status
Not open for further replies.

PeggySDay

Programmer
Apr 13, 2007
17
US
I must admit that I'm very green at programming and this may seem like a simple problem.

I have an index of documents in MS Word 2003 which are in a numbered list. I'd like to create a macro to go to each numbered document, select the document, and insert a hyperlink that references the document, which is saved in a directory. The list would look something like this:

1. Management Agreement
2. Deed of Trust
3. Pledge and Security Agreement

There are almost 300 documents so that's why I want to automate this project. The first document would be saved as 001.pdf, the second document would be saved as 002.pdf, and so on, which is on my hard drive.

Any help would be sincerely appreciated!

 
I wanted to show code I've already attempted. This code works in adding the hyperlink and correctly displays the anchor, however I'm clueless about how to change the address to match up with the filename:

Code:
   Selection.Find.ClearFormatting
    With Selection.Find
        .Text = "^p^#"
        .Replacement.Text = "^p"
        .Forward = True
        .Wrap = wdFindStop
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    Selection.Find.Execute
    Selection.MoveRight Unit:=wdWord, Count:=3
    Selection.Extend
    Selection.Extend Character:=Chr(13)
    Selection.MoveLeft Unit:=wdCharacter, Count:=1
      
    Set aHLink = ActiveDocument.Hyperlinks.Add(Anchor:=Selection.Range, _
    Address:=Selection.MoveLeft)
    Selection.Collapse



 
I am having trouble following this.

how to change the address to match up with the filename

So am I. WHERE is the filename? There does not appear to be any filename in the following:

1. Management Agreement
2. Deed of Trust
3. Pledge and Security Agreement

I used your code and...ummm...I am still not sure what you are doing.
This code works in adding the hyperlink and correctly displays the anchor
Really. It seems to make a hyperlink of "1" - using the list you gace.

I am not sure of what use that is.

Gerry
My paintings and sculpture
 
Thanks for your response, Gerry. [morning]

What I'd like the macro to do is to copy the number 1 that appears before Management Agreement and paste it into the address of the hyperlink and at some point add the zeros before the number 1 and the .pdf after the 1. So ultimately, the address in the hyperlink to the first document will be: 001.pdf.

Then to continue to the next document 2. Deed of Trust and copy the number 2, select the title Deed of Trust, insert a hyperlink, paste the 2, add in the two zeros 00 and the .pdf at the end. So that the address is: 002.pdf. And continue doing the same process with each document until it reaches the end of the document.

There is an additional issue in that when it comes to the two digit numbers (i.e., 10, 11, 12, etc.) and finally the three-digit numbers (i.e., 100, 101, 102, etc.) that it will add the appropriate number of zeros.

Hope that makes sense.
 
So ultimately, the address in the hyperlink to the first document will be: 001.pdf.
This is not much of an address.

If I understand you correctly:

1. You want to make a hyperlink with an address of 1

2. Edit that hyperlink address to 001.pdf

Without a path it is, again, not much of a hyperlink.

Hyperlinks need somewhere to point. 001.pdf does not qualify.

Gerry
My paintings and sculpture
 
You set the address for a hyperlink using the Address property. BTW: is your variable aHLink declared?
Code:
Dim aHLink As Hyperlink

'  other stuff

aHLink.Address = "c:\temp\blahblah.doc"
So you certainly can edit the address. It needs more than 001.pdf though.;

Gerry
My paintings and sculpture
 
I should give you some more background. Ultimately, this project will end up being saved to a CD. The CD will be set up to autoexecute and open the index of the documents. That is, the end user inserts the CD and automatically the Word index launches on screen. The end user will click on the hyperlinks to the documents, which then are launched into Adobe Acrobat (being they are pdf's). So the pathing to the pdf documents uses relative pathing. Relative pathing is used because depending on the end user's computer, the CD drive might be the "d" drive, or it might be the "e" drive or could be some other drive.

BTW, I'm unfamiliar with the hyperlink object.
 
I haven't heard back from anyone and I could really and truly use the help. I am so new to programming and am struggling with where to start. I hope I haven't offended you, Gerry. You started to help me, then I lost you. I absolutely in no way meant to be offensive. I've been up and down anything to do with hyperlinks and am coming up with nada. Even if someone could help me think through the logic (maybe I'm approaching this all wrong). What questions should I be asking myself when you begin something like this? Should I be looking for built-in methods? Do I look at the hyperlink object? I'm clueless, any help and I would be tremendously grateful!!! Thanks!!!
 
Oh I am not offended. I am on the road, on vacation actually. I am just addicted to Tek-Tips.

Hmmm. You have a problem with the relative paths.

However, I still have to say that I do not really understand what is going on.

You have a Word doc with this list...I think.

WHERE are these PDF coming from?? Is this part of the macro process? I am not getting where the actual pdf files are.
The first document would be saved as 001.pdf,
is throwing me off. "Would be"?????

The pdf files exist...or not?

If all you are doing is having a CD with an autoexecute to the Word document, AND that word doc is in the same folder as the pdf files, then you may be OK. You can have Word pick up the path of the current doc, and create the hyperlinks using the same drive/folder.

Gerry
My paintings and sculpture
 
Hi Peggy,

The following code will add the necessary hyperlinks to your document, pointing to the current folder. For the automatic linking code that I'll describe next, this is where they'll need to be.

Code:
Sub AddHyperlinks()
Dim oPara As Paragraph
Dim StrPara As Range
With ActiveDocument
    For Each oPara In .Paragraphs
        On Error GoTo ErrHandler
        If oPara.Range.Words(1).Text = (oPara.Range.Words(1).Text) ^ 1 Then
            Set StrPara = oPara.Range
            StrPara.MoveEnd wdCharacter, -1
            .Hyperlinks.Add Anchor:=StrPara, _
            Address:=Replace$(ActiveDocument.Path, "\", "\\") & _
            Format(oPara.Range.Words(1).Text, "000.pdf"), _
            SubAddress:="", ScreenTip:="", TextToDisplay:=StrPara.Text
        End If
ErrHandler:
    Next
End With

Having established the links, if you put the following code into your Word document, it will automatically update *all* links (not just hyperlinks) to point to the current folder whenever the document is opened. It even gives a progress report on the status bar, which might be useful since your document has lots of links:

Code:
Option Explicit
Dim SBar As Boolean           ' Status Bar flag
Dim TrkStatus As Boolean      ' Track Changes flag

Private Sub AutoOpen()
' This routine runs whenever the document is opened. It mainly calls others to do the real work.
' Prepare the environment.
Call MacroEntry
' Most of the work is done by this routine.
Call UpdateFields
' Set the saved status of the document to true, so that changes via this code are ignored. Since
' the same changes will be made the next time the document is opened, saving them doesn't matter.
ActiveDocument.Saved = True
' Go to the start of the document
Selection.HomeKey Unit:=wdStory
' Clean up and exit.
Call MacroExit
End Sub

Private Sub MacroEntry()
' Store current Status Bar status, then switch on temporarily.
SBar = Application.DisplayStatusBar
Application.DisplayStatusBar = True
' Store current Track Changes status, then switch off temporarily.
With ActiveDocument
    TrkStatus = .TrackRevisions
    .TrackRevisions = False
End With
' Turn Off Screen Updating temporarily.
Application.ScreenUpdating = False
End Sub

Private Sub MacroExit()
' Clear the Status Bar
Application.StatusBar = False
' Restore original Status Bar status
Application.DisplayStatusBar = SBar
' Restore original Track Changes status
ActiveDocument.TrackRevisions = TrkStatus
' Restore Screen Updating
Application.ScreenUpdating = True
End Sub

Private Sub UpdateFields()
' This routine sets the new path for external links.
Dim oRange As Word.Range
Dim oField As Word.Field
Dim OldPath As String
Dim NewPath As String
Dim i As Integer
i = 0
' Set the new path
NewPath = Replace$(ActiveDocument.Path, "\", "\\")
' Go through all story ranges in the document, including shapes, headers & footers.
For Each oRange In ActiveDocument.StoryRanges
' Go through the fields in the story range.
    For Each oField In oRange.Fields
        With oField
            ' Skip over fields that don't have links to external files
            If Not .LinkFormat Is Nothing Then
                ' Update the staus bar display
                i = i + 1
                Application.DisplayStatusBar = "Updating Link #: " & i
                ' Get the old path
                OldPath = Replace(.LinkFormat.SourcePath, "\", "\\")
                ' Replace the link to the external file
                .Code.Text = Replace(.Code.Text, OldPath, NewPath)
            End If
        End With
    Next oField
Next oRange
End Sub

Cheers

[MS MVP - Word]
 
Whoops - bug in the 'AddHyperlinks' code. Change:
Address:=Replace$(ActiveDocument.Path, "\", "\\") & _
to
Address:=ActiveDocument.Path & "\" & _

Cheers

[MS MVP - Word]
 
Wowee gazowee! I must say that my eyes are glazed over. I'm going to have to study this line by line and try to understand it. I won't be able to test your code until tomorrow when I get to work. I'll let you know how it works out.

I've had one college course on VB for Beginners. I work in a law firm and use Word 2003 mostly. Can you recommend a book for a novice?

Thanks again macropod, Peg
 
Gerry, thanks for writing. Don't mean to pester you while you're on vacation. I love this site, too. I just signed up about a week ago.

I'll give you an overview of this project I'm doing. I work in a law firm. Our real estate attorneys work on large closings, each closing generating sometimes hundreds of documents. My job is to scan each document into a PDF format. My working folder is on our server.

When the directory is completely configured with the autorun files, scanned pdf's and Word index, the project is burned to a CD.

When the end user places the CD into the drive, the Word index of documents opens up onscreen. You know the rest.

Anyway, I'm trying to automate the inserting of the hyperlinks because I'll be doing this everytime a closing comes my way.

Enjoy your vaca- Peg
 
Hi Peg,

It's a holiday here (Oz) tomorrow, so I may not be on-line either.

Cheers

[MS MVP - Word]
 
Hi Peg. Macropod beat me to it. His code does what I was suggesting. Have Word use the current path and build the hyperlinks.

I would point out that as this file is to be on a presumably finalized CD, and run from there, saving it is not relevant or possible anyway. It will work though as it will be the current document and active changes are OK.

The only thing missing - I think - is the incremental counter for the pdf file names. I will let macropod adjust that, since he posted the code.

Gerry
My paintings and sculpture
 
Hi Gerry,

The PDF counter is actually in there - it's derived from 'oPara.Range.Words(1).Text', where I've assumed the number at the start of the paragraph defines the PDF's number. More sequential than incremental but, if the paragraph numbers are incremental (as I'd expect them to be), that will take care of itself.

Cheers

[MS MVP - Word]
 

Greetings Macropod-

Looks like the time for you is about 4:00am (tomorrow). I'm in California, U.S.

I looked up your holiday, ANZAC Day, so you're probably busy with the holiday.

I tried to run the code and it breaks with this error message: Compile error: expected function or variable

On the line which reads: With [COLOR=red yellow]ActiveDocument[/color] (it highlights "ActiveDocument").


Here's the code I've inserted in its entirety:

Code:
Sub HyperlinkInsert()

Dim oPara As Paragraph
Dim StrPara As Range

With [COLOR=red yellow]ActiveDocument[/color]
    For Each oPara In .Paragraphs
        On Error GoTo ErrHandler
        If oPara.Range.Words(1).Text = (oPara.Range.Words(1).Text) ^ 1 Then
            Set StrPara = oPara.Range
            StrPara.MoveEnd wdCharacter, -1
            .Hyperlinks.Add Anchor:=StrPara, _
            Address:=ActiveDocument.Path & "\" & _
            Format(oPara.Range.Words(1).Text, "000.pdf"), _
            SubAddress:="", ScreenTip:="", TextToDisplay:=StrPara.Text
        End If
ErrHandler:
    Next
End With
End Sub

Please help. Thanks and Cheers- Peg
[ponder][flowerface]
 
Hi Peg,

I've run the code on two different systems - one with Word 2000 on Win 2000 and one with Word 2007 on Wind Vista, and both run correctly.

All I can suggest is that you check that your code is exactly as posted - sometimes copying of hte web can introduce extraneous hard space characters, so check for those too.

Cheers

[MS MVP - Word]
 

Thanks for the reply. I don't know whether this helps, but I'm running it on-

[ul square][li]Windows XP Professional[/li]
[li]Microsoft Office Word 2003 (Part of Microsoft Office Professional 2003)[/li]
[li]Microsoft Visual Basic 6.3[/li][/ul]

I've cursored through the code and I'm not seeing any extra spaces. Any other ideas?

Based on the error message, is there anything I can add to the With ActiveDocument line?

Thank you- Peg
[hairpull2]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top