Alphabetical list of paragraph headings with page numbers - generated by VBA

Good morning MS Word Experts,

I have a Word document of about 2100 lines long with over 400 paragraphs. It's essentially a long series of notes.

All I want is a macro-generated alphabetical list of all the paragraph headings and the page number on which I can find each item. The result needs to be in page 1 of the existing document. I also need to be able to run the macro as often as needed when I add new notes. I don't expect the macro to update the list, instead I would manually delete page 1 before running the macro.

I'm afraid I can't upload the file, however I can make all the paragraph headings one particular font and point size - for example, Tahoma - pt12

Patrick
LVL 45
patrickabAsked:
Who is Participating?
 
GrahamSkanRetiredCommented:
Here is my attempt at code to create an index. It steps through the paragraphs instead of using the Find. Patrick's code loops refinding the same entry.
Sub CreateIndex()
Dim rng As Range
Dim Para As Paragraph
Dim fld As Field
Dim idx As Index
Dim bNoIndex As String
 
Const strFont = "Tahoma"
Const sngSize = 12
Const bBold = True
 
'Set index entry for each paragaph with matching font and some text.
For Each Para In ActiveDocument.Paragraphs
    Set rng = Para.Range
    If rng.End - rng.Start > 1 Then
        If rng.Font.Size = sngSize Then
            If rng.Font.Name = strFont Then
                If rng.Font.Bold = bBold Then
                    rng.MoveEnd wdCharacter, -1
                    bNoIndex = True
                    For Each fld In rng.Fields
                        If fld.Type = wdFieldIndexEntry Then
                            bNoIndex = True
                            Exit For
                        End If
                    Next fld
                    If bNoIndex Then
                        ActiveDocument.Indexes.MarkEntry rng, rng.Text, rng.Text
                    End If
                End If
            End If
        End If
    End If
Next Para
'find existing index table
bNoIndex = True
For Each fld In ActiveDocument.Fields
    If fld.Type = wdFieldIndex Then
        Set rng = fld.Code
        rng.Collapse wdCollapseStart
        fld.Delete
        bNoIndex = False
        Exit For
    End If
Next fld
 
'Insert page break if necessary
If bNoIndex Then
    Set rng = ActiveDocument.Range(0, 0)
    rng.InsertBreak wdPageBreak
    Set rng = ActiveDocument.Range(0, 0)
End If
 
'create index table
Set idx = ActiveDocument.Indexes.Add(Range:=rng, HeadingSeparator:= _
        wdHeadingSeparatorNone, Type:=wdIndexIndent, RightAlignPageNumbers:= _
        True, NumberOfColumns:=1, IndexLanguage:=wdEnglishUK)
idx.TabLeader = wdTabLeaderDots
End Sub

Open in new window

0
 
Patrick MatthewsCommented:
Hello Patrick,

If your various index entries are "marked", then Word can automatically build an index, and then once the
index is built it can update the index very readily.

The code below marked all entries with Arial font, size 16, bold.  You can then go to the point where you
want the index to be and create it.  Later on, to update the index, all you need to do is right click it and
select 'update field'.

Regards,

Patrick
Sub MarkIndexEntries()
        
    Dim rng As Range
    Dim Counter As Long
    Dim HasIndex As Boolean
    
    Selection.HomeKey Unit:=wdStory
    
    Set rng = ActiveDocument.Content
    
    With rng.Find
        .ClearFormatting
        .Text = ""
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindStop
        .Format = True
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
        With .Font
            .Name = "Arial"
            .Size = 16
            .Bold = True
        End With
        Do
            .Execute
            If .Found Then
                HasIndex = False
                For Counter = 1 To rng.Fields.Count
                    If Left(rng.Fields(Counter).Code, 4) = " XE " Then
                        HasIndex = True
                        Exit For
                    End If
                Next
                If Not HasIndex Then
                    ActiveDocument.Indexes.MarkEntry rng, rng.Text, rng.Text
                End If
            Else
                Exit Do
            End If
        Loop
    End With
    
End Sub

Open in new window

0
 
GrahamSkanRetiredCommented:
Patrick (matthewspatrick) suggests building an set if indexes (indices?) but what you described can be done with a TOC if the paragraph headings use a heading style.

Have you tried using the inbuilt Table of Contents facility?
0
Cloud Class® Course: Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

 
patrickabAuthor Commented:
Patrick,
Thank you for your contribution. Unfortunately I have a clue as to how to make use of it. I have copied your macro into an ordinary VBA Module and run it. It never seems to stop and I can't see what it has done - perhaps the results aren't visible - I just dunno.
The trouble is that in large part I use MSWord just as a simple word processor. I have absolutely no idea how to get it to create Tables of Contents or Indexes. In my original question (this is a virtual repeat) I was told to read up on those features - somewhat defeats the object of asking a question here!
So how do I start on this project, make use of your macro and conclude it with a list of paragraph headings and the page numbers on which they can be found?
Regards
Patrick
0
 
GrahamSkanRetiredCommented:
If you are using 2003 or earlier, do Insert/Reference, Index and tables... and choose the Index or Table of Contents tab.
0
 
patrickabAuthor Commented:
Oops - should have been...
Patrick,
Thank you for your contribution. Unfortunately I haven't a clue as to how to make use of it. I have copied your macro into an ordinary VBA Module and run it. It never seems to stop and I can't see what it has done - perhaps the results aren't visible - I just dunno.
 The trouble is that in large part I use MSWord just as a simple word processor. I have absolutely no idea how to get it to create Tables of Contents or Indexes. In my original question (this is a virtual repeat) I was told to read up on those features - somewhat defeats the object of asking a question here!
So how do I start on this project, make use of your macro and conclude it with a list of paragraph headings and the page numbers on which they can be found? I am sure I don't need to supply a sample of the layout of the sort of document I have - nevertheless one is attached. Ignore the contents of the paragraphs - they are irrelevant to what I want to achieve - only the headings matter. I have used Tahoma12pt for the headings.
 Regards
 Patrick

Paragraph-headings-rqd-01.doc
0
 
patrickabAuthor Commented:
GrahamSkan,
Thanks for your input. I have looked where you have instructed but so far not managed to get it to do anything useful other than for it to tell me there's an error. I really don't know how to get it to work. It's seems really obscure to me. I need a step by step set of instructions.
Patrick
0
 
GrahamSkanRetiredCommented:
Your paragraph headings do not have a specific paragraph style.

Select one of them and choose Format/Styles and Formatting. In the Style task pane, hover the mouse over the box below the words 'Formatting of the Selected text'. A drop-down arrow will appear at the right of the box. (Why it isn't there all the time so that you don't have to hose over the whole screen looking for 'secret' buttons beats me.) Anyway, click on it and choose Modify...
In the format box, change the style type to Paragraph, and choose Heading 3 (say) for the 'Style based on:' Click OK and close the Style task pane.

Now put the cursor on the document at the start of the text (Ctrl+Home). Insert a page or a Next page section break. Return the cursor to the start of the document.  You should now be able to insert a TOC which lists the headings and the page numbers.
0
 
Patrick MatthewsCommented:
Graham,

I agree with you that at first blush this sounded more like a TOC.  However, I could not figure out how to get
a TOC to sort the items alpahbetically rather than by order of appearance.

Patrick: can you post a sample file?

Regards,

Patrick
0
 
Patrick MatthewsCommented:
Never mind, found the sample :)
0
 
GrahamSkanRetiredCommented:
Good point. I had forgotten the alphabetic bit. There isn't a switch to change the TOC order.
0
 
patrickabAuthor Commented:
>Patrick: can you post a sample file?
I posted one a little earlier but here it is again. Completely ignore the contents of the paragraphs as they are irrelelvant.
Patrick

Paragraph-headings-rqd-01.doc
0
 
patrickabAuthor Commented:
Patrick / Graham,
I have to say that the whole system is obscure in the extreme to produce a Table of Contents. The only trouble is that the TOC is not in alphabetical order. Any idea how I can achieve that. I tried copying and pasting into a table with the intention of then sorting it but it failed to paste the page numbers.
Patrick
0
 
patrickabAuthor Commented:
Patrick / Graham,
I've now figured it out - all I need to do is to copy and paste the TOC into a single celled Table and then sort it.
Thank you both for your help.
If there's a way of making use of your macro Patrick do please let me know. Although I have a vague idea about VBA in Excel, in Word I haven't a clue.
Patrick
0
 
Patrick MatthewsCommented:
Patrick,

Word VBA is *not* my forte.  I know enought to be dangerous, and I can sometimes muddle through recording
a macro and then cleaning the code, but that's about it.  I cannot figure out why my macro is working on my
test file but not on your sample.  Perhaps Graham can figure that out--he's probably forgotten more about Word
VBA than I would ever know in several lifetimes :)

Nice trick on coopting the TOC.  That could possibly be automated, but I'd leave that to Graham...

Regards,

Patrick
0
 
patrickabAuthor Commented:
Patrick,
Thanks for your efforts. MS Word's cleverer aspects leave me cold. The Help file is anything but that and I cannot be hacked to buy a book on MSWord. In short MSWord does a basic job for me and little more. Sure I can set up tables, and sometimes even formulae within the tables but there's usually little point in doing that when Excel does it 1000 times better.
I raised this as a question last week and got very annoyed with the potential answerer. His background was publishing - as a result he told me that I HAD to understand and use the MSWord terminology. He also told me to read up on TOC's and Indexes for MSWord. Rather defeated the object of asking the question in the first place. In fact I got so annoyed with him that I even received a rebuking email from a Mod! Ah well, such is life.
Regards
Patrick
0
 
patrickabAuthor Commented:
Graham,
Many thanks for that code - it works very well and is exactly what I was needing.
I will be asking a follow-up question and will post the link to it in my next comment.
Patrick
0
 
patrickabAuthor Commented:
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.