Pouria golshanrad
Pouria golshanrad

Reputation: 102

How insert multiple hyperlinks to one comment in MS WORD using C#?

This is my code. I can insert one hyperlink to per comment but i want insert multiple hyperlinks to one comment but i don't know how change my code.

using Microsoft.Office.Interop.Word;

     public void addCommentsToDocument(object start, object end, Hyperlink[] comments)
            {
                Range range = document.Range(ref start, ref end);
                object missing = System.Reflection.Missing.Value;
                for (int i = 0; i < comments.Length; i++)
                {
                    object url = comments[i].url;
                    object text = comments[i].Text;
                    Comment var = document.Comments.Add(range, text);
                    document.Hyperlinks.Add(var.Range, ref url, ref missing, ref missing, ref text, ref missing);
                }
            }

Upvotes: 0

Views: 898

Answers (1)

Cindy Meister
Cindy Meister

Reputation: 25663

The trick to adding additional content to a region in Word is to work with the Range object. Once a Comment is inserted, it has a Range. To append something to the end of the Range, similarly to working with a selection when typing, you need to "collapse" the Range to its end-point (like pressing the Right-Arrow key). For example:

object oEnd = WdCollapseDirection.wdCollapseEnd;
Comment var = document.Comments.Add(range, text);
Range rng = var.Range;

document.Hyperlinks.Add(rng, ref url, ref missing, ref missing, ref text, ref missing);
rng.Collapse(ref oEnd);
rng.Text = ", ";
rng.Collapse(ref oEnd);

Since you want this in a loop it would probably be better to add the Comment object before the loop - the Text parameter is optional, so pass ref missing - as well as the Comment.Range object. Then loop creating the hyperlink, collapsing, assigning text to separate one hyperlink from the next, and collapsing again for the next hyperlink.

Upvotes: 1

Related Questions