<CharlieDigital/> Programming, Politics, and uhh…pineapples

19Feb/07Off

Setting Links in Word Programmatically

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.

Posted by Charles Chen

Filed under: .Net Comments Off
Comments (0) Trackbacks (0)

Sorry, the comment form is closed at this time.

Trackbacks are disabled.