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

19Feb/070

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.

» Share
  • Print
  • Digg
  • StumbleUpon
  • del.icio.us
  • Facebook
  • Twitter
  • Google Bookmarks
  • LinkedIn

About Charles Chen

I'm a senior consultant with Paragon Computer Professionals. In a previous life, I was the lead developer at a startup building what became CSC's FirstPoint.
Filed under: .Net Leave a comment
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment

(All comments are moderated)

No trackbacks yet.