none
how can i get paragraphs which contains field? RRS feed

  • Question

  • in my document , i have inserted some field into heading paragraph like below picture

    the easiest way is iterate all off the paragraphs then check each paragraph's range, but this way is quite slowly, 

    foreach (Word.Paragraph p in doc.ListParagraphs){

         // check each list paragraph

    }

    get filed using docment.Fields property may be the fastest way, but  Field class does not have any property to get the paragraph which field locate in.

    is any other efficent way? thanks

    Saturday, March 15, 2014 8:23 AM

Answers

  • In VBA, you can use code like:

    Dim Fld As Field, Rng As Range
    For Each Fld In ActiveDocument.Fields
      Set Rng = Fld.Code
      With Rng
        .Collapse wdCollapseStart
        .Start = ActiveDocument.Range.Start
        MsgBox .Paragraphs.Count
      End With
    Next

    Note: some fields can contain multiple paragraphs of their own (eg a TOC), yet only account for a short range.


    Cheers
    Paul Edstein
    [MS MVP - Word]

    • Marked as answer by sendreams Saturday, March 15, 2014 10:03 AM
    Saturday, March 15, 2014 9:44 AM

All replies

  • In VBA, you can use code like:

    Dim Fld As Field, Rng As Range
    For Each Fld In ActiveDocument.Fields
      Set Rng = Fld.Code
      With Rng
        .Collapse wdCollapseStart
        .Start = ActiveDocument.Range.Start
        MsgBox .Paragraphs.Count
      End With
    Next

    Note: some fields can contain multiple paragraphs of their own (eg a TOC), yet only account for a short range.


    Cheers
    Paul Edstein
    [MS MVP - Word]

    • Marked as answer by sendreams Saturday, March 15, 2014 10:03 AM
    Saturday, March 15, 2014 9:44 AM
  • hi, macropod

    thank you very much

    it solved my problem, thanks again.

    Saturday, March 15, 2014 10:03 AM