Word vba paragraph number

I need find an specific text in my document and get paragraph number position

This is for Excel VBA

Sub exportardatos()
'Paso 1: Declare las variables
Dim Paragraphe As Object, WordApp As Object, WordDoc As Object, WordTable As Object, WordRange As Object
File = "C:UserslperDocumentsFormExp.docx"

 On Error Resume Next

    'creationsession Word
    Set WordApp = GetObject(class:="Word.Application")

    'Clear the error between errors
    Err.Clear
    If WordApp Is Nothing Then Set WordApp = CreateObject(class:="Word.Application")

      If Err.Number = 429 Then
        MsgBox "Microsoft Word could not be found, aborting."
        GoTo EndRoutine
      End If

  On Error GoTo 0
    WordApp.Visible = True
    WordApp.Activate
    'open the file .doc
    Set WordDoc = WordApp.Documents.Open(File)


    'Word Enumerated Constants
    Const wdReplaceAll = 2
        WordApp.Documents("FormExp.docx").Activate
        Dim nParag As Long
        Set WordRange = WordApp.ActiveDocument.Paragraphs(1).Range

        For Each WordRange In WordDoc.StoryRanges
         With WordApp.Selection.Find
                .ClearFormatting
                .Replacement.ClearFormatting
                .Text = "Legal"
                .Wrap = wdFindContinue
                .Execute
                Do While .Execute = True
                nParag = WordRange(0, Selection.Paragraphs(1).Range.End).Paragraphs.Count
                MsgBox (nParag)
                Loop

         End With
        Next WordRange

EndRoutine:
        'Optimize Code
          Application.ScreenUpdating = True
          Application.EnableEvents = True

        'Clear The Clipboard
          Application.CutCopyMode = False

    'Set WordDoc = Nothing
    'Set WordApp = Nothing
MsgBox ("Ready")
End Sub

I get code error 438

Cindy Meister's user avatar

asked Jun 10, 2019 at 15:58

rafapmx's user avatar

1

Here’s a quick example of how to get the paragraph number. Notice that you don’t have to Activate the Word document to get this to work.

Public Sub Exportardatos()
    Dim filename As String
    filename = "C:UserslperDocumentsFormExp.docx"

    Dim wordApp As Object
    Set wordApp = GetObject(class:="Word.Application")
    If wordApp Is Nothing Then
        Set wordApp = CreateObject(class:="Word.Application")
        If Err.Number > 0 Then
            MsgBox "Microsoft Word cannot be found!", vbOKOnly + vbCritical
            Exit Sub
        End If
    End If

    Dim wordDoc As Object
    Dim searchRange As Object
    Set wordDoc = wordApp.Documents.Open(filename)
    Set searchRange = wordDoc.Range

    With searchRange.Find
        .ClearFormatting
        .Replacement.ClearFormatting
        .Text = "Legal"
        .Wrap = 0                     '=wdFindStop
        While .Execute(FindText:="Legal", Forward:=True)
            If .found Then
                Debug.Print "found in paragraph " & GetParNum(wordDoc, .Parent)
            End If
        Wend
    End With
End Sub

Function GetParNum(ByRef doc As Object, ByRef r As Object) As Integer
    '--- based on http://www.vbaexpress.com/kb/getarticle.php?kb_id=59
    Dim rParagraphs As Object
    Dim CurPos As Long

    r.Select
    CurPos = doc.Bookmarks("startOfSel").Start
    Set rParagraphs = doc.Range(Start:=0, End:=CurPos)
    GetParNum = rParagraphs.Paragraphs.Count
End Function

answered Jun 10, 2019 at 16:58

PeterT's user avatar

PeterTPeterT

8,1671 gold badge17 silver badges38 bronze badges

0

  • Remove From My Forums
  • Question

  • for example. If the paragraph is «3.1. sdasdasdasdasd». I need to retrieve the «3.1». How can I do that with VBA. Of course, that paragraph had taken a list style.

Answers

  • Hi Sefler,

    Try:

    Sub ReportThisListPara()
    Application.ScreenUpdating = False
    Dim i As Integer, j As Integer, xRefs As Variant, TmpRef
    ‘Get the CrossReferenceItems collection
    xRefs = ActiveDocument.GetCrossReferenceItems(wdRefTypeNumberedItem)
    With Selection
      If .Range.ListParagraphs.Count = 0 Then Exit Sub
      .Collapse wdCollapseEnd
      On Error Resume Next
      ‘Loop through the CrossReferenceItems collection to find the current paragraph
      For i = 1 To UBound(xRefs)
        If ActiveDocument.ListParagraphs(i).Range.End = .Paragraphs.First.Range.End Then
          MsgBox ActiveDocument.ListParagraphs(i).Range.ListFormat.ListString
          Exit For
        End If
      Next
    End With
    Application.ScreenUpdating = True
    End Sub


    Cheers
    Paul Edstein
    [MS MVP — Word]

    • Marked as answer by

      Tuesday, January 25, 2011 10:48 AM

If You want to learn how to find a word or phrase in Word file and get its paragraph or word number stay here, You’ve come to the right place!

Find word and get its paragraph number from Word file

Some time ago I wrote about finding phrase in Word or .pdf files, but now we want something more…

Long story short

Recently, I got inspired by topic from StackOverflow, much about finding a word position in the Word file. When I saw this, I wanted to try my skills and create a tool, which finds a word or whole phrase in the Word file and returns its position – number of paragraph or word.

Background

To get things more complicated and be consistent with my website name I wanted to create it in Excel.

Imagine, that in column “A” You store the words, in column “B” locations of Word files You want to search for and in column “C” macro returns words position.

First things first

At the beginning we need to declare variables, which will stand for Word variables: Word application, Word document and Word document ranges.

Dim wd As Word.Application
Dim wdDoc As Word.Document
Dim rng As Word.Range, rng2 As Word.Range, rParagraphs As Word.Range

Get the search info

After all needed declarations let’s get search phrase srcwd and Word file localization wdfile.

Dim txt As String, wdfile As String, srcwd As String
Dim CurPos As Long, GetParNum As Long

wdfile = ThisWorkbook.Sheets(1).Range("B1")
srcwd = ThisWorkbook.Sheets(1).Range("A1")

Create Word objects

To open Word file from Excel, You need to create Word application object and set its document to next variable.

Set wd = CreateObject("Word.Application")
Set wdDoc = wd.Documents.Open(wdfile)

Assign content

Later on set all Word file content range to rng.

Set rng = wdDoc.Content

Text of this document can be taken out from this range variable.

We got opened target Word file and all of its text assigned to variable. Now we can start to seek for chosen phrase and get its paragraph or word number. To do it we will use function .Find

With rng.Find
    .Text = srcwd
    .Forward = True
    .Execute
End With

This will find and select the next occurrence (.Forward = True) of the searched word (srcwd).

Remember about the .Execute, because without it won’t work at all, regardless of parameters number!

Get paragraph number

Finally, we can get the paragraph or word number!

First, we need to set the cursor in the end of the found word. In other case macro will not count the paragraph, which the word is in it!

CurPos = rng.Words(1).End

Next let’s set the range from the beginning of the document to the position of cursor.

Set rParagraphs = wdDoc.Range(Start:=0, End:=CurPos)

Thanks to that we got range containing everything up to searched word and now all we have to do is count the number of paragraphs!

GetParNum = rParagraphs.Paragraphs.Count

If You want to know what is its word number just change Paragraphs to Words.

GetWordsNum = rParagraphs.Words.Count

Whole code

There is one matter left to do in the end of our code. We have to save somewhere the paragraph number. Let’s write it down to the column C, after that close the document with no changes and quit Word application (see end of below code).

Option Explicit

Sub src4Word()

Dim wd As Word.Application
Dim wdDoc As Word.Document
Dim rng As Word.Range, rng2 As Word.Range
Dim rParagraphs As Word.Range
Dim txt As String, wdfile As String, srcwd As String
Dim CurPos As Long, GetParNum As Long

wdfile = ThisWorkbook.Sheets(1).Range("B1")
srcwd = ThisWorkbook.Sheets(1).Range("A1")

Set wd = CreateObject("Word.Application")
Set wdDoc = wd.Documents.Open(wdfile)
Set rng = wdDoc.Content

With rng.Find
    .Text = srcwd
    .Forward = True
    .Execute
End With

CurPos = rng.Words(1).End
Set rParagraphs = wdDoc.Range(Start:=0, End:=CurPos)
GetParNum = rParagraphs.Paragraphs.Count

ThisWorkbook.Sheets(1).Range("C1") = GetParNum
wdDoc.Close 0
wd.Quit

End Sub

Summary

Now You know how to find a word or phrase in Word file and get its paragraph or even its word number! It looks so easy! You can use this code to the other variations, for example to get whole text of the searched word paragraph. The choice is yours!

I’m very advanced in VBA, Excel, also easily linking VBA with other Office applications (e.g. PowerPoint) and external applications (e.g. SAP). I take part also in RPA processes (WebQuery, DataCache, IBM Access Client Solutions) where I can also use my SQL basic skillset. I’m trying now to widen my knowledge into TypeScript/JavaScript direction.
View all posts by Tomasz Płociński

 

Word

Get Line and Paragraph Number

Ease of Use

Intermediate

Version tested with

97 

Submitted by:

Steiner

Description:

This is a collection of three small functions that provide the line number on the current page, the abolute line number in the document, and the paragraph number in the document. 

Discussion:

Sometimes you need to refer to the line number of a certain bookmark or other object. Here, we provide three methods of functionality that MS should have included, but has not. Our sample file provides messageboxes to report the location. Likely, you will not use this method, but will use this code with other code to perform your task(s). 


Code:

instructions for use

			

Sub WhereAmI() MsgBox "Paragraph number: " & GetParNum(Selection.Range) & vbCrLf & _ "Absolute line number: " & GetAbsoluteLineNum(Selection.Range) & vbCrLf & _ "Relative line number: " & GetLineNum(Selection.Range) End Sub Function GetParNum(r As Range) As Integer Dim rParagraphs As Range Dim CurPos As Long r.Select CurPos = ActiveDocument.Bookmarks("startOfSel").Start Set rParagraphs = ActiveDocument.Range(Start:=0, End:=CurPos) GetParNum = rParagraphs.Paragraphs.Count End Function Function GetLineNum(r As Range) As Integer GetLineNum = r.Information(wdFirstCharacterLineNumber) End Function Function GetAbsoluteLineNum(r As Range) As Integer Dim i1 As Integer, i2 As Integer, Count As Integer, rTemp As Range r.Select Do i1 = Selection.Information(wdFirstCharacterLineNumber) Selection.GoTo what:=wdGoToLine, which:=wdGoToPrevious, Count:=1, Name:="" Count = Count + 1 i2 = Selection.Information(wdFirstCharacterLineNumber) Loop Until i1 = i2 r.Select GetAbsoluteLineNum = Count End Function

How to use:

  1. Copy the code above.
  2. Open your document.
  3. Hit Alt +F11 to open the Visual Basic Editor (VBE).
  4. Double-click your document’s name at left.
  5. Choose Insert-Module from the menu.
  6. Paste the code you copied.
  7. Close the VBE.

 

Test the code:

  1. Place your cursor somewhere inside the document.
  2. Hit Tools-Macro-Macros and double-click WhereAmI to display a dialog pointing out your current position.

 

Sample File:

Position.zip 7.78KB 

Approved by mdmackillop

This entry has been viewed 263 times.

Old

06-29-2015, 08:05 AM

brice
brice is offline

Get paragraph number from macro Windows 7 64bit Get paragraph number from macro Office 2010 32bit

Novice

Get paragraph number from macro

 

Join Date: Jun 2015

Posts: 3

brice is on a distinguished road

Default

Get paragraph number from macro


Dear all,

I would want to retrieve from word macro the number associated to a paragraph in my document, but I am completely blocked on that point.

I joined a small sample of a file with same style as the original. I already wrote all code needed to parse the info I need to collect from my document except that, when I iterate through the Document.Paragraphs collection, I would want to be able to retrieve the paragraph number (in this example 1.1.1.1) when reaching the paragraph of the sample.

I tried the ListStyle, OutlineLevel, etc. properties, but with no success.

Any help would be very appreciated !

Thanks in advance,

Brice

Reply With Quote

Old

06-29-2015, 10:49 PM

Default


You are probably going to have to do a bit of lateral thinking to grab this number from the autonumbered field in your document. The following macro should work for the paragraph at the cursor

Code:

Dim ofld As Field
Dim orng As Range
    Set ofld = Selection.Paragraphs(1).Range.Fields(1)
        ofld.Unlink
        Set orng = Selection.Paragraphs(1).Range.Previous
        orng.Collapse 0
        orng.MoveEndUntil Chr(9)
        orng.Select
        MsgBox orng.Text
        ActiveDocument.Undo

__________________
Graham Mayor — MS MVP (Word) (2002-2019)
Visit my web site for more programming tips and ready made processes www.gmayor.com

Reply With Quote

Old

06-30-2015, 02:08 AM

brice
brice is offline

Get paragraph number from macro Windows 7 64bit Get paragraph number from macro Office 2010 32bit

Novice

Get paragraph number from macro

 

Join Date: Jun 2015

Posts: 3

brice is on a distinguished road

Default


Thank you very much for your answer. I tested and it seems to work like a charm. But I have still two small questions :

First, I have big difficulties understanding your code. In particular, why do you make the unlink, previous and collapse stuff ?

Second, imagine that now, I want to programmatically find the paragraph whose number is 1.2.3.4. By adapting your code, I can iterate through all paragraphs of document, extract the paragraph number with your code, and check if it matches. But is there a more efficient way to do this ?

Thanks in advance.

Regards,

Brice

Reply With Quote

Old

06-30-2015, 03:08 AM

Default


The number is created by a field { AUTONUMLGL }, but that field does not readily give up its result to VBA e.g.

Code:

Dim ofld As field
    For Each ofld In ActiveDocument.Fields
        If ofld.Type = wdFieldAutoNumLegal Then
            MsgBox ofld.Result
        End If
    Next ofld

shows no values

The example code therefore converts the field in the selected paragraph to plain text, which of course is readily accessible from VBA, which is what the range commands are about.

It may well be inefficient but it works and is reasonably fast. To process all the paargraphs then the following should work — it does with your sample.

Code:

Dim ofld As field
Dim orng As Range
Dim oPara As Paragraph
Const strFind As String = "1.1.1." 'The number sequence to find
    For Each oPara In ActiveDocument.Range.Paragraphs
        If oPara.Range.Fields.Count > 0 Then
            Set ofld = oPara.Range.Fields(1)
            If ofld.Type = wdFieldAutoNumLegal Then
                ofld.Unlink
                Set orng = oPara.Range.Previous
                orng.Collapse 0
                orng.MoveEndUntil Chr(9)
                If orng.Text = strFind Then
                    orng.Select
                    MsgBox orng.Text
                    Exit For
                End If
                ActiveDocument.Undo
            End If
        End If
    Next oPara

__________________
Graham Mayor — MS MVP (Word) (2002-2019)
Visit my web site for more programming tips and ready made processes www.gmayor.com

Reply With Quote

Old

06-30-2015, 03:29 AM

brice
brice is offline

Get paragraph number from macro Windows 7 64bit Get paragraph number from macro Office 2010 32bit

Novice

Get paragraph number from macro

 

Join Date: Jun 2015

Posts: 3

brice is on a distinguished road

Default


Thank you very much for those explanations.

Regards,

Brice

Reply With Quote

Like this post? Please share to your friends:
  • Word using letters create
  • Word using letters certain letters
  • Word using french dictionary
  • Word using all the vowels
  • Word uses for english language