none
Check if particular style appears in the document fails for a single paragraph document. RRS feed

  • Question

  • Hi,

        I am trying to find if the document contains any text with style "heading 1". Using the below code works for almost all cases:

    Function checkStyleExistense(doc As Document)

         Dim range As Range = doc.Content

         With range.Find

                .Style = doc.Styles("Heading 1").NameLocal

         End With

         Return (range.Find.Execute())

    End Function

    But it fails if the document contains only one paragraph with style "Heading 1". It works as soon as I insert a paragraph break.

    Can I know if there is a workaround to achieve this.

    Thanks,

    Prem

    Wednesday, March 15, 2017 3:30 PM

All replies

  • Hi Prem-,

    try to use the code below. it can work for a single paragraph too without entering a paragraph break.

    also able to find and loop through all the "Heading 1" paragraphs in document.

    Sub demo3()
    
     Dim txt As String
     Dim p As Paragraph
    
     With ActiveDocument
     For Each p In .Paragraphs
     If p.Style = "Heading 1" Then
     txt = p.Range.Text
     MsgBox "Found=" & txt
     End If
     Next p
     End With
    End Sub
    

    Output:

    you can modify the code as per your requirement.

    Regards

    Deepak


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Thursday, March 16, 2017 1:56 AM
    Moderator
  • With VBA, you might use something like:

    Function CheckStyleExistense(Doc As Document)
    Dim bFnd As Boolean: bFnd = False
    With Doc.Range
      With .Find
        .Style = "Heading 1"
        .Execute
        bFnd = .Found
      End With
      If .Paragraphs.First.Style = "Heading 1" Then bFnd = True
    End With
    CheckStyleExistense = bFnd
    End Function

    This should be much faster than automatically checking all paragraphs in a document. I'll leave it to you to adapt the code to your needs.


    Cheers
    Paul Edstein
    [MS MVP - Word]

    Thursday, March 16, 2017 3:22 AM