问题
I have a Word 2010 template. When used, a form is presented to the user and they are prompted to enter a string in a textbox named BugNumTextBox. Upon command, I wish to construct a URL, create a hyperlink, and insert that into the document.
The desired insertion point (anchor) is a Rich Text Content Control with a tag name of "foo". For the address parameter I have attempted:
1) To specify the range of the content control
2) To specify the range of a bookmark (named BugNum) that I created inside of the content control.
Neither have worked, resulting in run-time errors.
Can anyone suggest a method to achieve this?
Below is a non-working example of method 2 above.
ActiveDocument.Hyperlinks.Add Anchor:=.Bookmark("BugNum").Range, Address:= _
"http://bugs.fubar.net/show_bug.cgi?id=" & BugNumTextBox, _
SubAddress:="", ScreenTip:="", TextToDisplay:=""
Thank you much.
回答1:
Why don't you access the ContentControls Object Collection instead.
Something like:
Dim ccRtxt As ContentControl
Set ccRtxt = ActiveDocument.ContentControls(1)
ccRtxt.Range.Hyperlinks.Add ccRtxt.Range, _
"http://stackoverflow.com/questions/26538906/" & _
"add-hyperlink-into-word-content-control-with-vba"
Above will work on the scenario you describe where you only have 1 ContentControl.
If you have many such objects, you can do this:
Dim ccRtxt As ContentControl
For Each ccRtxt In ActiveDocument.ContentControls
If ccRtxt.Tag = "foo" Then
ccRtxt.Range.Hyperlinks.Add ccRtxt.Range, _
"http://stackoverflow.com/questions/26538906/" & _
"add-hyperlink-into-word-content-control-with-vba"
End If
Next
This adds this question as hyperlink address in your Rich Text Content Control.
You can adjust the address property to suit your needs. HTH.
来源:https://stackoverflow.com/questions/26538906/add-hyperlink-into-word-content-control-with-vba