Random Thoughts of a Scatterbrain.
 Monday, February 19, 2007

Setting Links in Word Programmatically

2/19/2007 1:58:10 PM (Eastern Standard Time, UTC-05:00)

Since I didn't find anything on this topic via Google...

Just a quick "how to" on setting links in Microsoft Word programmatically (in this case, C#):

public void CheckRuntime() {
    object reference = null;

    try {
        reference = Marshal.GetActiveObject("Word.Application");
    }
    catch (COMException) {
        System.Console.Out.WriteLine("No instances found...");
    }

    if (reference != null) {
        try {
            System.Console.Out.WriteLine("Found running instance!");

            ApplicationClass wordRuntime = (ApplicationClass)reference;

            System.Text.StringBuilder buffer = new StringBuilder();
            foreach (Document document in wordRuntime.Documents) {
                buffer.AppendFormat("{0}|", document.Name);

                if (wordRuntime.Selection != null) {
                    System.Console.Out.WriteLine("Selected text: \"{0}\"",
                        wordRuntime.Selection.Text);

                    object optional = Missing.Value;
                    object url = "http://www.google.com/";

                    if(wordRuntime.Selection.Hyperlinks.Count == 0) {
                        wordRuntime.Selection.Hyperlinks._Add(
                            wordRuntime.Selection.Range,
                            ref url,
                            ref optional
                        );
                    }
                }
            }

            System.Console.Out.WriteLine(
                string.Format("Currently open documents are: {0}",
                buffer.ToString().Trim('|'))
            );
        }
        finally {
            Marshal.ReleaseComObject(reference);
        }
    }
}

The code is wrapped in a function call I'm using for testing. The key part of this is detecting the currently selected text and using the ApplicationClass.Selection and then invoking _Add. The method takes three parameters. Make sure that your first parameter is a Range class instance, your second parameter is passed by reference, and your third parameter (the SubAddress) is set to System.Reflection.Missing.Value.

This should set the text point to any input URL.

Name
E-mail
Home page

Comment (HTML not allowed)  
Enter the code shown (prevents robots):

RSS 2.0 Atom 1.0 CDF