Odd behavior in word macro
So what I'm trying to do, is programatically create hyperlinks in a word document and point them to text written as a heading in another part of the word document. Easy enough to do by right clicking and selecting the correct option. So I figured I'd start by recording a macro doing exactly that. This is the result:
ActiveDocument.Hyperlinks.Add Anchor:=Selection.Range, Address:="", _
SubAddress:="_Yet_more_text.", ScreenTip:="", TextToDisplay:="Link "
Now the wierd part. Creating the hyperlink through the menu works fine (ie. I click it and it goes where i expect it to), but if I run the above macro, the link that is created sends me to the top of the document instead of to the specified heading! Almost like it doesn't recognize the address.
Has anyone seen this before and can point out what I'm doing wrong? I'm using Word 2000 SP3, On XP SP2 (I've tried the same thing on several different machines with different OS's and different Word versions with the same result).
Thanks
Re: Odd behavior in word macro
Welcome to the Forums.
So does it at least go to the correct page? Or just take you to the top of the current page?
The anchor is tied to selected text when you recorded the macro. So if you dont have anything selected it wont have an anchor to go to.
VB Code:
'This part of your code.
Anchor:=Selection.Range 'If empty then it goes nowhere.
Re: Odd behavior in word macro
The text is selected at the time the link is created, so the hyperlink appears to be anchored to something.
No, it does not go to the correct page. If I create the link via the recorded macro, then click on the link, it takes me to the top of the document. So for example if its a 20 page document, I'm on page 6 when I click the link, it takes me to the top of page 1.
Of course if I select the text, rick click and select Hyperlink, then it works just fine. :ehh:
Re: Odd behavior in word macro
It seems that if you change the name of the text that you want to Link by putting different text in the TextToDisplay part of the code then it will not work.
So if you have text called Link1 then in your code the TextToDisplay MUST be the Same - i.e. - 'Link1'
If you change this to something else then it doesn't work !
Examples -
Text in Document = Link1 - Selected text for Hyperlink
Then this WILL work !!
VB Code:
ActiveDocument.Hyperlinks.Add Anchor:=Selection.Range, Address:="", _
SubAddress:="_Header1", ScreenTip:="", TextToDisplay:="Link1"
This WONT work !!
VB Code:
ActiveDocument.Hyperlinks.Add Anchor:=Selection.Range, Address:="", _
SubAddress:="_Header1", ScreenTip:="", TextToDisplay:="Link1Changed"
Oh and DONT have spaces in your selection ie TextToDisplay:="Link "