In my previous article, we saw, how can we add a custom ribbon to word and how to add buttons and actions to those buttons.
Here is the link to the previous article.
In this article, we will build on top of the previous one.
After adding custom ribbon and custom buttons, on click of those buttons, we will add some logic to work on the content of Microsoft word document.
We will learn how to get contents of a word document runtime and work on those documents, like scanning them.
This can help in adding validations in word documents/ content validation. Also, we can use this to add some custom text at various places of document in bulk.
So let’s get going with this new topic.
1. Let’s add a new button to our ribbon now by adding the button in CustomActionsRibbon.xml (validateButton in below)
<?xml version="1.0" encoding="UTF-8"?>
<customUI xmlns="http://schemas.microsoft.com/office/2009/07/customui" onLoad="Ribbon_Load">
<ribbon>
<tabs>
<tab idMso="TabAddIns">
<group id="ContentGroup" label="Content">
<button id="textButton" label="Insert Content" screentip="Text" onAction="OnTextButton" supertip="Inserts text content at the cursor location."/>
<button id="msgButton" label="Show Message" screentip="Message Box" onAction="OnMsgButton" supertip="Shows Message Box."/>
<button id="validateButton" label="Validate" screentip="Validate Contents" onAction="OnValidateButton" supertip="Validates Document Contents."/>
</group>
</tab>
</tabs>
</ribbon>
</customUI>
2. Add Action method for this button in class CustomActionsRibbon.cs
public void OnValidateButton(Office.IRibbonControl control) {
Microsoft.Office.Interop.Word.Application wdApplication = Globals.ThisAddIn.Application;
Microsoft.Office.Interop.Word.Document activeDoc = wdApplication.ActiveDocument;
if (!Regex.IsMatch(activeDoc.Paragraphs.First.Range.Text, "Title", RegexOptions.IgnoreCase)) {
MessageBox.Show(@ "First Paragraph must have text "
"Title"
" inside");
}
}
In the above method, we are trying to match our first paragraph in the document to make sure that it should have word “Title” within.
3. Build app and run it.





Join the conversation! Your thoughts help the community grow.