Search code examples
c#ms-wordoffice-interopmathtype

How to find math equation in Word file and if found then highlighted it using vsto c#


How can I find math equation in Word file?

Please suggest for the same.

My output will be getting like this:

enter image description here


Solution

  • Use the below C# code to highlight all MathType equation in yellow color. Before using the this code add using Word = Microsoft.Office.Interop.Word; in namespace declaration in your class file.

    public bool FindAndHighlightMathtypeEquation(ref Word.Range myRange)
        {
            try
            {
                int inlineShapesCount = myRange.InlineShapes.Count;
                if (inlineShapesCount > 0)
                {
                    for (int i = 1; i <= inlineShapesCount; i++)
                    {
                        Word.InlineShape currentShape = myRange.InlineShapes[i];
                        Word.Range currentShapeRange = currentShape.Range;
                        Word.WdInlineShapeType typeOfCurrentShape = currentShape.Type;
    
                        if (typeOfCurrentShape != Word.WdInlineShapeType.wdInlineShapeEmbeddedOLEObject)
                        {
                            continue;
                        }
    
                        if (!currentShape.Field.Code.Text.Trim().ToLower().Contains("equation"))
                        {
                            continue;
                        }
    
                        currentShapeRange.Select();
                        currentShapeRange.Application.Selection.Range.HighlightColorIndex = Word.WdColorIndex.wdYellow;
                    }
                }
    
                MessageBox.Show("Process Completed");
    
            }
            catch (Exception)
            {
                throw;
            }
            return true;
        }