Search code examples
c#ms-wordoffice-interop

C# How to get automated number of heading in Word Interop


I have code (as soon below) that loops through all the paragraphs and finds a specific string. When I find the string, I print out the automated number of the header it belongs to. The problem, I want the header number as well and can't figure out how to get it. Code here:

Edit: Cleaned up code with working content

string LastHeader = "";

foreach (Paragraph paragraph in aDoc.Paragraphs)
{
    Microsoft.Office.Interop.Word.Style thisStyle = 
           (paragraph.Range.get_Style() as Microsoft.Office.Interop.Word.Style);
    if (thisStyle != null && thisStyle.NameLocal.StartsWith("Heading 2"))
    {
        LastHeader = paragraph.Range.ListFormat.ListString + " " + 
                        paragraph.Range.Text.Replace("\"", "\"\"").Replace("\r", "");
    }
    else
    { 
        string content = paragraph.Range.Text;

        for (int i = 0; i < textToSearch.Count; i++)
        {
            if (content.Contains(textToSearch[i]))
            {
                // Do stuff here
            }
        }
    }
}

Solution

  • Every time I re-read your information I get the feeling I'm not understanding completely what you're asking, so the following may contain more information than you're looking for...

    To get the numbering of a specific Paragraph:

    paragraph.Range.ListFormat.ListString
    

    Word has some built-in bookmarks that can give you information that is otherwise a lot of work to determine. One of these is \HeadingLevel. This gets the first paragraph formatted with a Heading style that precedes a SELECTION. And that's the sticky part, because we don't really want to be making selections... But it dates back to the old WordBasic days when code mimicked user actions, so we're stuck with that.

    textToAnalyse.Select
    aDoc.Bookmarks("\HeadingLevel").Range.ListFormat.ListString
    

    The bookmark call, itself, will NOT change the selection.

    The other option I see, since you're already looping the Paragraphs collection, would be to check the paragraph.Range.Style and, if it begins with the string "Heading" (assuming that's not used otherwise in these documents' styles) save the ListFormat.ListString so that you can call on it if your condition is met.

    I do have to wonder, however, why you're "walking" the paragraphs collection and not using Word's built-in Find capability as that would be much faster. It can search text AND (style) formatting.