Deborah's Developer MindScape






         Tips and Techniques for Web and .NET developers.

August 31, 2009

Bolding Text in Microsoft Word using .NET

Filed under: C#,Microsoft Word,VB.NET @ 1:42 pm

One of the common requirements in working with Microsoft Word from .NET is to bold some text. This is often required to draw attention to specific words within the document.

This code example highlights any instances of the word "was". It can be changed to instead highlight any word you desire.

In C#:

// Add to the top of the code file
using Word = Microsoft.Office.Interop.Word;

// Add to a subroutine
Word.Application Wd;
Word.Document doc;
object missingValue = Missing.Value;

// Start Word and get Application object
Wd = new Word.Application();

// Add a new document
doc = Wd.Documents.Add(ref missingValue,ref missingValue, 
                       ref missingValue,ref missingValue );

// Write some text
Wd.Selection.TypeText("Once upon a time there was a document. " +
                      "The document was fair and fine." +
                      "The document was short.");

// Bold the specified word
foreach (Word.Range w in doc.Words)
{
    if (w.Text.Trim() == "was")
        w.Font.Bold = 1;
}

// Save
object fileName = @"test1.docx";
doc.SaveAs(ref fileName,
            ref missingValue, ref missingValue,
            ref missingValue, ref missingValue,
            ref missingValue, ref missingValue,
            ref missingValue, ref missingValue,
            ref missingValue, ref missingValue,
            ref missingValue, ref missingValue,
            ref missingValue, ref missingValue,
            ref missingValue);

// Close
doc.Close(ref missingValue, ref missingValue, ref missingValue);
doc = null;
Wd.Quit(ref missingValue, ref missingValue, ref missingValue);

// Clean up
// NOTE: When in release mode, this does the trick
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect() ;

In VB:

‘ Add to the top of the code file
Imports Word = Microsoft.Office.Interop.Word

‘ Add to a subroutine
Dim Wd As Word.Application
Dim doc As Word.Document

‘ Start Word and get Application object
Wd = New Word.Application

‘ Add a new document
doc = Wd.Documents.Add

‘ Write some text
Wd.Selection.TypeText("Once upon a time there was a document. " & _
                      "The document was fair and fine." & _
                      "The document was short.")

Bold the specified word
For Each w As Word.Range In doc.Words
    If (w.Text.Trim() = "was") Then
        w.Font.Bold = 1
    End If
Next

‘ Save
doc.SaveAs("test1.docx")

‘ Close
doc.Close()
doc = Nothing
Wd.Quit()

‘ Clean up
‘ NOTE: When in release mode, this does the trick
GC.WaitForPendingFinalizers()
GC.Collect()
GC.WaitForPendingFinalizers()
GC.Collect()

In both of these examples, the code starts Word, creates a new Word document, and writes some text into the document. It then loops through the words in the document and bolds any that match "was". You can, of course, change this to any word.

The code then saves the document. Since no directory was found, it defaults to the My Document folder.

Notice the missingValue variable in the C# code that is not in the VB code. VB supports default parameters, but C# does not. So any time a parameter is defined for a Word method, C# must provide it. VB will use the default parameter values.

NOTE: A new feature in C# 4.0 (Visual Studio 2010) allows for default parameters in C# as well, dramatically simplifying the C# code that interacts with Word or Excel.

Enjoy!

8 Comments

  1.   Farabi — November 18, 2009 @ 5:18 pm    Reply

    Nice one

  2.   houshang — December 14, 2009 @ 11:09 pm    Reply

    hello
    this solution needs a long time to process so use the contents object to change font.

  3.   Kamlesh — February 8, 2010 @ 6:20 am    Reply

    Hi..

    I will be obliged if you could help in making a macro in MS word which will highlight already specified words “like he, his, him, man, male, etc.” in the current document.

    Thanks

    Kamlesh_ssstrans@hotmail.com

  4.   DeborahK — February 8, 2010 @ 4:02 pm    Reply

    Hi Kamlesh –

    Thank you for visiting my blog.

    I primarily code with .NET, so I don’t know how to convert this .NET code to work as a MS Word macro.

    Maybe if someone else here does they could post an example?

  5.   Ramprasad — February 24, 2011 @ 1:07 am    Reply

    Hi
    This article helped me to complete 90% of the requirement. thank You.I have a small query. Can u pls clarify it.
    If i have serach like ‘document was ….I want to blod this entire word ‘document was ‘…..
    In your example u r doing bold for ‘Was’… In my case i want to do two words as shown above.
    Please clarify….

  6.   Ronalee — June 29, 2011 @ 5:15 pm    Reply

    Smack-dab what I was lokoing for—ty!

  7.   DespeiL — November 4, 2013 @ 2:24 pm    Reply

    Have this error in C#:”
    The name ‘Missing’ does not exist in the current context”
    That you missed somthing or i dont understend where to get “Missing: object?

  8.   DeborahK — November 4, 2013 @ 3:53 pm    Reply

    Hi Despeit –

    Check out this link for more information on the Missing class.

    http://msdn.microsoft.com/en-us/library/system.reflection.missing.value(v=vs.100).aspx

    You may be missing a reference to System. Reflection?

RSS feed for comments on this post. TrackBack URI

Leave a comment

© 2014 Deborah's Developer MindScape   Provided by WPMU DEV -The WordPress Experts   Hosted by Microsoft MVPs