Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleRemove hyperlinks from a Word file in VB .NET
DescriptionThis example shows how to remove hyperlinks from a Word file in VB .NET
KeywordsWord, Microsoft Word, Office, Microsoft Office, hyperlink, VB .NET
CategoriesOffice, Miscellany
 
This program requires a reference to the Word object model. Select Project/Add Reference. Click the COM tab and select "Microsoft Word 11.0 Object Library" (or whatever version you have on your system).

To remove the hyperlinks, the program opens a Word server and uses it to open the Word document. It loops over the document's stories. For each story, it loops through Hyperlinks collection, calling each one's Delete method.

A slightly odd thing happens in this code. The call to Open takes a parameter declared as an Object. If you try to pass in txtFile.Text, Visual Basic complains that it cannot convert an Object into a String. But wait. You're trying to do the opposite: pass a String in as an Object variable. That should work because a String is a type of Object (it inherits from Object).

The trick is that this parameter is declared without the ByVal keyword. That means it is passed by reference and the Open routine might change the Object's value. It cannot do that if you pass it a String instead of an Object so it complains. A bit backwards but it makes some sense.

 
Private Sub btnRemoveHyperlinks_Click(ByVal sender As _
    System.Object, ByVal e As System.EventArgs) Handles _
    btnRemoveHyperlinks.Click
    Dim word_app As Word.Application
    Dim word_doc As Word.Document
    Dim doc_story As Word.Range
    Dim hyper_link As Word.Hyperlink

    ' Make a Word server object.
    word_app = New Word.Application
    word_app.Visible = False

    ' Open the Document.
    word_doc = _
        word_app.Documents.Open(DirectCast(txtFile.Text, _
        Object))

    ' Loop over all document stories.
    For Each doc_story In word_doc.StoryRanges
        For Each hyper_link In doc_story.Hyperlinks
            hyper_link.Delete()
        Next
    Next doc_story

    ' Save and close the document.
    word_doc.Close(True)

    ' Clean up.
    word_app.Quit()
    MessageBox.Show("Done")
End Sub
 
For more information on programming Word and other Microsoft Office applications with VBA, see my book Microsoft Office Programming: A Guide for Experienced Developers.
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated