Solved

Using VBA add hyperlinks to an index

Posted on 2009-05-19
51
1,051 Views
Last Modified: 2012-05-07
In a previous question - link:
http://www.experts-exchange.com/Software/Office_Productivity/Office_Suites/MS_Office/Word/Q_24414185.html

The solution by GrahamSkan produced a sorted index of paragraph headings. It's in the attached file.

What I would now like is for each entry in the sorted index to be a hyperlink so that I can just click on it and be taken directly to the item. However I need these hyperlinks to be added using VBA - so automating the production of the sorted, hyperlinked index of paragraph headings.

Patrick
0
Comment
Question by:patrickab
  • 28
  • 21
  • 2
51 Comments
 
LVL 4

Expert Comment

by:Xcone
ID: 24420425
I think you forgot to actually attach the file. See attached code for an example on how to add hyperlinks using VBA. If you need help to implement it, let me know.
Sub CreateHyperLink()

  Dim DocStart As Range

  Dim DocEnd As Range

  

  Set DocStart = ActiveDocument.Range

  DocStart.Collapse wdCollapseStart

  

  Set DocEnd = ActiveDocument.Range

  DocEnd.Collapse wdCollapseEnd

  

  DocStart.Text = "Start of Doc"

  DocEnd.Text = "End Of Doc"

  

  ActiveDocument.Hyperlinks.Add DocStart, ActiveDocument, DocEnd

End Sub

Open in new window

0
 
LVL 45

Author Comment

by:patrickab
ID: 24420536
>I think you forgot to actually attach the file.
Thanks for the reminder - file now attached.

Paragraph-headings-rqd-01.doc
0
 
LVL 45

Author Comment

by:patrickab
ID: 24420561
Xcone,
Thanks for the macro. I've just run it but it didn't do what I needed. Perhaps a tweak of some sort will get it to do what I need. If you run the 'Create Index' macro first you will see the index on page 1. It's the index that I need converting into hyperlinks.
Patrick
0
 
LVL 4

Expert Comment

by:Xcone
ID: 24422743
My previous code was just an example on how to add hyperlinks from code in general, just to get you on the way. Not to replace or be merged with graham's code. This time I've got graham's code and added my code to it to get the whole proces working. Just delete all the code and replace it with the attached code.

There are a few notes you should know about:
1) The additional code could run have poor performance. Not to worry, it should only noticed in VERY large documents. Unfortunatly it's the price you pay for this feature.
2) The Index which is created by Graham, partially used the built-in Word Index, which could be manually extended by marking additional Index Entries. It would update on the fly. The update on the fly would remove all the hyperlinks I add to it. Therefore, after completion, the index is no longer automated by Word. The only way to update it, is by running the code again.

If you have any questions, let me know.
Option Explicit
 

Sub CreateIndex() 'written by Graham Skan - May 2009, Modified for hyperlinks by Xcone - May 2009

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

'Old code written by Graham Skan (commented) - May 2009, Modified for hyperlinks by Xcone - May 2009

bNoIndex = True

If ActiveDocument.Bookmarks.Exists("XE__Index") Then

  Set rng = ActiveDocument.Bookmarks("XE__Index").Range.Duplicate

  rng.Collapse wdCollapseStart

  ActiveDocument.Bookmarks("XE__Index").Range.Delete

  bNoIndex = False

End If

'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 = wdTabLeaderDashes
 

'Add hyperlinks (new code by Xcone, May 2009)

Dim character As Range

Dim pagenum As Integer

Dim pagerange As Range

Dim indexnamerange As Range

Dim idxRange As Range

Dim indexEntryRange As Range

Dim uniqueBookmarkInt As Integer

Dim bmk As Bookmark
 

For Each bmk In ActiveDocument.Bookmarks

  If Left(bmk.Name, 4) = "XE__" Then

    bmk.Delete

  End If

Next
 

uniqueBookmarkInt = 0
 

Set idxRange = idx.Range

idxRange.Fields.Unlink
 

idxRange.Bookmarks.Add "XE__Index", idxRange
 

For Each Para In idxRange.Paragraphs

  If InStr(1, Para.Range.Text, vbTab, vbTextCompare) > 0 Then

    Set rng = Para.Range

    rng.MoveStartUntil vbTab, rng.End - rng.Start

    

    Set indexnamerange = Para.Range

    indexnamerange.MoveEndUntil vbTab, indexnamerange.Start - indexnamerange.End

    indexnamerange.MoveEnd wdCharacter, -1

    

    ' Separate hyperlink for each page number

    While rng.Text <> ""

      Set character = rng.Duplicate

      character.Collapse wdCollapseStart

      character.MoveEnd wdCharacter, 1

      

      If IsNumeric(character.Text) Then

        pagenum = CInt(character.Text)

        Set pagerange = FindPageRange(pagenum)

        

        For Each fld In pagerange.Fields

          If fld.Type = wdFieldIndexEntry Then

            If StrComp(Trim(fld.Code.Text), "XE """ & indexnamerange.Text & """", vbTextCompare) = 0 Then

              Set indexEntryRange = fld.Code.Paragraphs(1).Range

              indexEntryRange.Bookmarks.Add "XE__" & uniqueBookmarkInt, indexEntryRange

              ActiveDocument.Hyperlinks.Add character, "", "XE__" & uniqueBookmarkInt

              uniqueBookmarkInt = uniqueBookmarkInt + 1

              Exit For

            End If

          End If

        Next

      End If

      

      rng.MoveStart wdCharacter, 1

    Wend

  End If

Next
 

End Sub
 

Function FindPageRange(ByVal APageNum As Integer) As Range ' By Xcone - May 2009

  ' find page range

  Dim r As Range

  Dim rec As Rectangle

  Dim hasRange As Boolean

  

  hasRange = False

  

  For Each rec In ActiveDocument.ActiveWindow.ActivePane.Pages(APageNum).Rectangles

    If rec.Range.StoryType = wdMainTextStory Then

      If hasRange Then

        If r.Start > rec.Range.Start Then

          r.Start = rec.Range.Start

        End If

        If r.End > rec.Range.End Then

          r.End = rec.Range.End

        End If

      Else

        Set r = rec.Range

        hasRange = True

      End If

    End If

  Next

  

  Set FindPageRange = r

End Function

Open in new window

0
 
LVL 76

Expert Comment

by:GrahamSkan
ID: 24425819
I could see that it would be quite complex. Because one index can often refer to several pages, there is no in-built hyperlinking in Index tables.

A TOC can have hyperlinks, so it might be worth having another look your original idea of a sorted TOC.
0
 
LVL 4

Expert Comment

by:Xcone
ID: 24426735
My code takes that into account. And index adds all pages where the index occurs. There's a separate hyperlink for each page. The only thing which is not possible is multiple marks of the same index on 1 page. But since you're allready on the correct page, I can't image it's a problem.
0
 
LVL 45

Author Comment

by:patrickab
ID: 24427514
It's late here so I'll have a look tomorrow.
0
 
LVL 45

Author Comment

by:patrickab
ID: 24435447
Xcone,
Apologies for not testing your macros earlier - been doing all sorts.
I copied and pasted all the code you gave above into a new VBA Module, edited the old macros so as to prevent conflicting names and ran the new one(s). It produces the sorted list of paragraph headings but 'errors' on the word 'Recatangle' in the function 'FindPageRange. Unfortunately the Help file tells me zip about that word so I'm dependant on you to sort it out.
Patrick
0
 
LVL 45

Author Comment

by:patrickab
ID: 24435459
'Recatangle' = 'Rectangle'
 
0
 
LVL 76

Expert Comment

by:GrahamSkan
ID: 24435974
Sorry Xcone. I didn't mean to denigrate your contribution. I was trying to point out to PatrickAB, who had already suggested (in another question) a solution using a TOC, the advantage of that approach.

Word is designed around the concept that whatever the author enters as text, it will still make sure at re-pagination/printing time that line folding and page breaks occur at appropriate places.

For this reason, some data - including page numbers, that depend on the pagination result is, naturally, only valid until the next re-.pagination
0
 
LVL 45

Author Comment

by:patrickab
ID: 24436255
I appreciated the comment as MS Word is 'black box' to me...
0
 
LVL 4

Expert Comment

by:Xcone
ID: 24437363
Well, I don't have much experience using the pages and rectangles. In fact, it's the first time I've used them but was suprised how well they work ... over here. Because of my limited knowledge on these objects I'm not sure why the error occurs. Probably a difference in Word versions ( I use Word 2007).

Can you post the error message that occurs?

On a side note: I've looked into the other post, and noticed you guys (Patrick and Graham) figured it out how to alphabeticly sort a TOC. That would seem like a very good solution indeed, as it provides built-in hyperlink support.

Graham, I'm well aware (though not fully knowing) on the Word pagination routines, and the fact page numbers could be invalid after a single small change in text. I did not however, considered this a problem, since a manual update would be executed after a change in the document. I do appreciate your effort and help in making the solution better and do not take offence by your response. I was just explaining my motivations back to you :-)
0
 
LVL 45

Author Comment

by:patrickab
ID: 24439392
>Probably a difference in Word versions ( I use Word 2007).
I should have stated that I'm using MS Word 2002 so I have no doubt that's the problem. There's no error message when the macro fails, it just halts and 'yellow lines' on the word 'Rectangle'. I have all the updates installed but I guess that some features are not included. Any further thoughts - perhaps I should revert to the sort of a TOC?

0
 
LVL 4

Expert Comment

by:Xcone
ID: 24440093
I'm really sorry, I had the code for a sorted TOC allmost done, when a crash occured and lost my entire progress. I do not have any time at this moment to redo it. I don't expect to for the rest of the day. Perhaps Graham can take it over. Otherwise you'll have to wait till tomorrow.
0
 
LVL 45

Author Comment

by:patrickab
ID: 24440367
I'm really not in a hurry - take your time.
0
 
LVL 4

Expert Comment

by:Xcone
ID: 24444798
Hi, I've been able to remake it in the meantime. See the attached code. Run it by executing "CreateSortedTOC".

There could be a problem though. The trick you used to sort a TOC... insert it in a 1 celled table, and then sort it... That trick doesn't work for me. I get an error stating a table containing a field cannot be sorted. This error appears when trying it manually as well as running from code. Now, I HOPE it's (again) a Word version difference, as in, not allowed in 2007, but still allowed in older versions. So it's worth a shot :-)

I've marked a line in comments. "f.unlink", near the end of the CreateSortedTOC sub. By enabling it, the TOC will be converted to text, and can then be sorted. But it's no real use, as the unlink command also removes the desired hyperlinks.......

Just give it a go, and if it's still not working, I'll try again using yet another approach.
Option Explicit
 

Public Const HeadingStyleName = "PowerToolsHeading"

Public Const HeadingStyleFontName = "Tahoma"

Public Const HeadingStyleFontSize = 12

Public Const HeadingStyleFontBold = True

Public Const SortedTOCBookmark = "SortedTOC"
 

Sub CreateSortedTOC()

  Dim r As Range

  Dim t As Table

  Dim f As Field

  Dim p As Paragraph

  Dim s As Style

  

  ' Create style if it doesn't exists allready

  Set s = GetStyle(HeadingStyleName)

  If s Is Nothing Then

    ' Create a 'spare' enter clean of formatting. Otherwise the new style will

    ' copy any inproper font settings currently applied to the selection.

    Set r = ActiveDocument.Range

    r.Collapse wdCollapseStart

    r.InsertBefore vbNewLine

    r.Style = wdStyleNormal

    r.Select

    

    Set s = ActiveDocument.Styles.Add(HeadingStyleName, WdStyleType.wdStyleTypeParagraph)

    s.Font.Name = HeadingStyleFontName

    s.Font.Size = HeadingStyleFontSize

    s.Font.Bold = HeadingStyleFontBold

    

    r.Delete

  End If

  

  ' Apply styles to headings

  For Each p In ActiveDocument.Paragraphs

    Set r = p.Range

    If r.End - r.Start > 1 Then

      If r.Font.Size = HeadingStyleFontSize Then

        If r.Font.Name = HeadingStyleFontName Then

          If r.Font.Bold = HeadingStyleFontBold Then

            p.Style = HeadingStyleName

          End If

        End If

      End If

    End If

  Next

  

  ' Remove current sorted TOC if it exists

  If ActiveDocument.Bookmarks.Exists(SortedTOCBookmark) Then

    ActiveDocument.Bookmarks(SortedTOCBookmark).Range.Delete

  End If

  

  ' Create table for sorted TOC

  Set r = ActiveDocument.Range

  r.Collapse wdCollapseStart

  Set t = r.Tables.Add(r, 1, 1)

  Set r = t.Range

  r.Collapse wdCollapseEnd

  r.InsertBreak WdBreakType.wdPageBreak

  Set r = t.Range

  r.MoveEnd wdCharacter, 2

  r.Bookmarks.Add SortedTOCBookmark, r

  

  ' Add TOC to table and sort it

  Set r = t.Cell(1, 1).Range

  r.MoveEnd wdCharacter, -1

  Set f = r.Fields.Add(r, WdFieldType.wdFieldTOC, "\h \z \t """ & HeadingStyleName & ";1""")

  f.Update

  

  ' This line will unlink the field thus converting it to normal text, but you'll lose the hyperlinks as well

  ' f.Unlink

  

  t.Cell(1, 1).Select

  Selection.MoveEnd wdCharacter, -1

  Selection.Sort False, "Paragraphs", wdSortFieldAlphanumeric, wdSortOrderAscending

End Sub
 

Function GetStyle(ByVal AStyleName As String) As Style

  On Error GoTo Except

  

  Set GetStyle = ActiveDocument.Styles(AStyleName)

Except:

End Function

Open in new window

0
 
LVL 4

Expert Comment

by:Xcone
ID: 24444830
Oh, forget to tell you (though you probably would've guessed it). This code doesn't use the other code, so you can discard the other code, or backup it, or put this code in yet another module. Should work either way.
0
 
LVL 45

Author Comment

by:patrickab
ID: 24446452
Xcone,
My goodness you are putting in a lot of effort on this question - much appreciated. However please don't hesitate to stop and let me know when you've had enough of this subject. After all there comes a time when it's no longer worth the candle.
I'm afraid it prodiced "Error! No table of contents entries found." So I ran your older macro to create the Sorted TOC and then tried your latest macro - but it didn't do anything useful.
Patrick
0
 
LVL 4

Expert Comment

by:Xcone
ID: 24451963
That's a different error than I expected. Are the headings still formatted as 'Tahoma, 12pt, bold'? This is still required for this code to work.
0
 
LVL 45

Author Comment

by:patrickab
ID: 24454082
>Are the headings still formatted as 'Tahoma, 12pt, bold'?
Yep, all headings 'Tahoma, 12pt, bold'
0
 
LVL 4

Expert Comment

by:Xcone
ID: 24455548
Hmm, weird. The code should create a style, apply it to all the headings formatted as  'Tahoma, 12pt, bold' and finally create a TOC using all occurances of this style.

Could you run the code on a document and upload the result. Just to verify some things and hopefully find out which part causes the error?

PS. I put in this "effort" because I want to. I strongly feel like I'm able to solve this, and I like the challenge. If I didn't like these things, I wouldn't have signed in.
0
 
LVL 45

Author Comment

by:patrickab
ID: 24457225
Xcone,
>I put in this "effort" because I want to. I strongly feel like I'm able to solve this, and I like the challenge. If I didn't like these things, I wouldn't have signed in.
Thank you for that response. I was only leaving the door open in case you were fed-up with the challenge.
I've run your latest macro 'CreateSortedTOC' - file now attached.
Patrick

Paragraph-headings-rqd-01.doc
0
 
LVL 4

Expert Comment

by:Xcone
ID: 24457568
Ah, the IndexEntries are still present, and they do not share the same formatting. Therefore the search for headings that should have the style applied failed. Meaning no headings with styles, and so no entries for the TOC.

The index entries are no longer required and can be removed. So either you run the macro "CreateSortedTOC" on the original document, which does not have these index entries, or you run the attached code ("RemoveIndexEntries") once, which will remove the Index entries for you. After they're removed, run the macro "CreateSortedTOC" again.
Sub RemoveIndexEntries()

  Dim f As Field

  

  For Each f In ActiveDocument.Fields

    If f.Type = wdFieldIndexEntry Then

      f.Delete

    End If

  Next

End Sub

Open in new window

0
 
LVL 45

Author Comment

by:patrickab
ID: 24457747
Xcone,
>...or you run the attached code ("RemoveIndexEntries") once, which will remove the Index entries for you. After they're removed, run the macro "CreateSortedTOC" again.
I've done that and I get exactly the same error message as in the last file I uploaded for you. I have also removed all the paragraph headings' formatting manually and re-instated one by one manually - and then run "CreateSortedTOC" again, but it still produces the same error message.
I am testing the macros on the last document I uploaded so if you could run your macros on that file and then upload the finished file that would be ideal.
Patrick
0
 
LVL 4

Expert Comment

by:Xcone
ID: 24457794
I've attached the doc file with the styles applied which allows for the generation of the TOC with hyperlinks.

As stated before, I cannot sort the TOC because of this error: "Word cannot sort fields in the selection." It appears in a popup (see attached image). Since you were able to do this manually ( and I cannot ) there's a slight chance it'll work in the Word version you're using. Just run the macro "CreateSortedTOC" yet again.
Paragraph-headings-rqd-01-Change.doc
CannotSortFields.jpg
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 45

Author Comment

by:patrickab
ID: 24457829
I get the error message as in the attached .jpg.
MWSnap-006-2009-05-23--14-47-09.jpg
0
 
LVL 4

Expert Comment

by:Xcone
ID: 24457926
Are you able to sort the table manually like you did before? If so, could you record it as a macro. I'll be able to merge your recorded macro with the current code and then it should be done.

To record a macro, goto Tools > Macro > Record macro.
Then sort the table manually
Then stop recording, either by Tools > Macro > Stop recording, or by pressing the square on the Commandbar that appeared when starting to record.
Then open VBA editor and expand the project "Normal". A module called "NewMacros" should've been created (if it wasn't allready there). Paste the macro you've just created here.
0
 
LVL 4

Expert Comment

by:Xcone
ID: 24458188
I've changed 2 more things in the code. It should now produce the desired result without depeding on Word versions.

The 1st change should be a safer way to apply styles, preventing the problem we had before.
The 2nd change removes the issue of not being able to sort the TOC. It basicly removes the TOC, but leaves the hyperlinks in tact. If this step still fails, I would still like to receive the recorded macro as requested in my previous post.
Paragraph-headings-rqd-01-Change.doc
0
 
LVL 45

Author Comment

by:patrickab
ID: 24459482
Xcone,
I have copied your macros into my file and attempted to run them, but they give the same error as last reported. What am I doing wrong? File attached...
Patrick

Paragraph-headings-rqd-02.doc
0
 
LVL 4

Expert Comment

by:Xcone
ID: 24461745
I don't think you're doing anything wrong. I think it's just Word 2007 responding differently to some commands then older versions of Word. So I think the mayor problem is that we're running different versions. Alas, I do not have Word 2002 at hand, otherwise I would've made this code in the Word 2002.

Anyway, I've yet again done some coding, which you can find in the attached file. This time I've added additional types of sorting and added some messages to track on where it goes wrong or how it succeeds. You'll probably get multiple messages, I only need to know the last one.
Paragraph-headings-rqd-01-Change.doc
0
 
LVL 45

Author Comment

by:patrickab
ID: 24465423
The result that is in the file you have uploaded is exactly what I was hoping for. However when I run the macro "CreateSortedTOC", it reports "There appear to be no entries in the TOC. Please verify the result." and then places in a single-celled table "Error! No table of contents entries found."
0
 
LVL 4

Expert Comment

by:Xcone
ID: 24465891
Do you execute the macro in the same document I've sent you, or do you run it in your own version of the document?

If you haven't tried in it my version, could you please try that now?

In your own version, after you've run the macro, could you verify that the headings have the style "PowerToolsHeading" applied.

If the style is applied and the TOC still shows no entries, could you try to manually create a TOC. The TOC should have the style "PowerToolsHeading" applied to the 1st level. Then refresh it. Does it have any entries now?

If you're having problems with these steps (I don't know your experience with Word..), let me know and I'll explain the steps you have to take in more detail.

0
 
LVL 45

Author Comment

by:patrickab
ID: 24467127
>Do you execute the macro in the same document I've sent you, or do you run it in your own version of the document?
I ran it in your file

>If you haven't tried in it my version, could you please try that now?
I did that and that's what I reported on.

>In your own version, after you've run the macro, could you verify that the headings have the style "PowerToolsHeading" applied.
I have now tried your latest macro in my file and obtained exactly the same error messages. The paragraph heading are Tahoma 12pt, whereas the the document heading is TNR 24pt. However none of the paragraph headings have a 'style' as you told me to delete the styles. Let me know if they should be reinstated.

>If the style is applied and the TOC still shows no entries, could you try to manually create a TOC. The TOC should have the style "PowerToolsHeading" applied to the 1st level. Then refresh it. Does it have any entries now?
If I apply a style to all the headings and then manually insert a TOC ( with or without hyperlinks) it does it OK. However now if I copy and paste the TOC into a single-celled table I can no longer sort it - odd as I could before.

>If you're having problems with these steps (I don't know your experience with Word..), let me know and I'll explain the steps you have to take in more detail.
I think I'm OK with the steps even though I usually use Word as just a word processor. About the furthest I ever go with it is to create mailing labels in an Excel / MS Word mailmerge. In fact I'm pretty good at doing that!
 
 
0
 
LVL 4

Expert Comment

by:Xcone
ID: 24475518
I think there's a mixup in terms here. Let me clarify myself.

I previously asked you to remove the index entry marks. These marks are fields. You can toggle these on or off by pressing Alt+F9. Any fields that look like; { XE "Sometext" } is an index entry mark.

A style is a formatting definition, which can be applied to text and/or entire paragraphs. Styles are not 'physicly' present like index entry marks are. To find out which style is applied to a paragraph, put your cursor on the paragraph, then goto menu 'Formatting' > item 'Styles and Formatting'. The styles pane should open to the right of the screen (default). All the available styles are listed in this pane. The one applied to the current paragraph has a border around it; here an example image.
http://sbarnhill.mvps.org/WordFAQs/images/S&Fpane.gif

The code I keep altering and sending you, should create a style called "PowerToolsHeading" to the document, and apply it to all paragraphs with the formatting 'Tahoma, 12pt, bold'. This step is really important as a TOC can only reference paragraphs with a style applied (usually the built-in Heading 1, 2 and 3, but in this case it's "PowerToolsHeading".

An Index as used in the previous attempt, can only reference Index entry marks. Because we're no longer using an index, these marks are useless. In fact, they're tricky to the solution, as it appeared they have different formatting then the heading they're put on, meaning it's harder to detect the formatting from code. Thus being tricky to detect if the style "PowerToolsHeading" should be applied. This problem should no longer persist however. The code should take it into account now.


With the information above, are you're answers still valid?

If so, could you try to run the code (where the TOC fails), then manually apply the style to the headings (using the styles pane) and then manually refresh the TOC, by putting your cursor on it, and pressing F9.

I have the feeling we're really close now, probably one or two 'bumps' to solve :-)
0
 
LVL 45

Author Comment

by:patrickab
ID: 24477874
I did indicate I know little about MS Word - I'm learning slowly! Let me have a look at your instructions and the document again - I'll be back...
0
 
LVL 45

Author Comment

by:patrickab
ID: 24478019
Thanks for the explanations.
Attached is your file after I have:
1. Deleted the sorted TOC
2. Checked that there are no Indices - using ALT+F9.
3. Ensured that all paragraph heading have the "PowerToolsHeading" style applied to them
4. Run the CreateSortedTOC macro
>With the information above, are you're answers still valid?
I believe so.

0
 
LVL 45

Author Comment

by:patrickab
ID: 24478026
Oops - file now attached.
Paragraph-headings-rqd-01-Change.doc
0
 
LVL 4

Expert Comment

by:Xcone
ID: 24484933
Well, the benifit of the table is really gone then. I've altered the code to no longer use a table to create the TOC in. And who knows, maybe the table is the cause the TOC will not update properly.
Paragraph-headings-rqd-01-Change.doc
0
 
LVL 45

Author Comment

by:patrickab
ID: 24485228
The result in that file is exactly what is wanted. What I'm not clear about is which macro produced it. I've tried various macros but so far without success.
0
 
LVL 4

Expert Comment

by:Xcone
ID: 24488189
The result in that file is the result when the macro "CreateSortedTOC" is executed. It gives that result for me anyway. Why it's still not working for you is still a mystery for me. With a bit of luck, I can spend a few minutes at my job on this matter. I have Word 2002 available to me there.

Was it still the same result? "Error! No table of contents entries found." ?
0
 
LVL 45

Author Comment

by:patrickab
ID: 24488871
>Was it still the same result? "Error! No table of contents entries found." ?
Yes, precisely that.
0
 
LVL 45

Author Comment

by:patrickab
ID: 24508283
Xcone,
Would you like me to award the points and so close this question?
Patrick
0
 
LVL 4

Expert Comment

by:Xcone
ID: 24508474
You seduce me to the dark side. =P

I can't seem to put my finger on the problem. I've been able to test my own script on Word 2002 in the meantime, and encountered no problems. Good chance there's a setting switched wrong or some other minor thing which blocks the TOC from properly updating. But this could be a search in a haystack.

I have one other idea though. Let us try this one. If this fails we'll call it "unsolvable" and I'll leave it to you of I deserve the points :)

This approach basicly removes the TOC as Word knows it, but now I create one fully manually. Since it's the TOC that appears to fail atm. maybe a manually generated TOC will get what you need. I've attached the file. There's one or two messages about sorting when executing the code. Ignore those for the moment. Also, the pagenumbers aren't aligned to the right side of the page. Finally, if the TOC get's too large (larger then 1 page) the pagenumbers in the TOC might be a page off. Please ignore these fails for the moment. I want to know if this runs correct before putting too much effort in it.
Paragraph-headings-rqd-01-Change.doc
0
 
LVL 45

Author Comment

by:patrickab
ID: 24508590
>and I'll leave it to you of I deserve the points :)
...not yet even read the whole of your contribution. Have no fear you deserve the full points and an A grade whatever the outcome...

0
 
LVL 45

Author Comment

by:patrickab
ID: 24512671
OK, I've run the macro and it gave 2 MsgBoxes - 'Trying to sort automatically'  and 'Autosort succeeded'. The result was a completely scambled document - see attached file. I think we should give up at this point... What d'you reckon?

Paragraph-headings-rqd-01-Change.doc
0
 
LVL 45

Author Comment

by:patrickab
ID: 24512686
I think I misunderstood your instructions. I have now created a TOC manually and then run the macro - see attached file. I think it's sorting according to page numbers rather than the items - but I'm not sure.
 

Paragraph-headings-rqd-01-Change.doc
0
 
LVL 4

Expert Comment

by:Xcone
ID: 24513080
This is quite .. unexpected .. and besides that, really odd too! I'm getting more confident some setting is screwing things up. I know 2 settings in particular that often cause problems.

Look for menu 'Tools' > Item 'Options' > Tab 'Editing'.

Please make sure 'Typing replaces selected text' is enabled, and 'smart cut and paste' is disabled. Then try again. If it still fails, please post a screenshot of this screen so I may review other settings that could have influence.

PS. I was unclear about the 'manually' part. I meant I do not use the builtin TOC feature of Word, but created my own from code. The only action you had to take was to execute the correct macro in the correct document.
0
 
LVL 45

Author Comment

by:patrickab
ID: 24513721
>PS. I was unclear about the 'manually' part. I meant I do not use the builtin TOC feature of Word, but created my own from code. The only action you had to take was to execute the correct macro in the correct document.
It was a bit ambiguous but it dodn't matter as I tried it both ways.
>Please make sure 'Typing replaces selected text' is enabled, and 'smart cut and paste' is disabled. Then try again.
Done that but it doesn't make it work.
>If it still fails, please post a screenshot of this screen so I may review other settings that could have influence.
See screenshot below
BTW - I have once again tried creating a TOC manually, pasting (unformatted text)  it into a single celled table and then sorting it - all successfully.


MWSnap-006-2009-05-31--20-58-50.jpg
0
 
LVL 4

Accepted Solution

by:
Xcone earned 500 total points
ID: 24519955
I hate to admit it, but I can't solve it. Your settings as shown in the screenshot are fine. So I can't find out from here what the cause is of this deviant behaviour. The best way to solve it now, is to get someone on site to look at the problem. Maybe re-ask the question and let another Expert take a look at it. Maybe he/she as other ideas that could help.
0
 
LVL 45

Author Comment

by:patrickab
ID: 24522409
Xcone,
You have been brilliant. Your patience and perseverance have been terrific. I wish I could award you more than 500 points for sheer persistance. Thank you very much for trying so hard.
I won't be asking for any further help on this subject as it has been totally exhausted and so is answer in its own right.
Many thanks again,
Patrick
0
 
LVL 45

Author Closing Comment

by:patrickab
ID: 31582900
Despite not finding a solution the effort was terrific. In its own right it is a valuable answer in that it shows that at the moment a sorted TOC cannot be done as I wanted.
0

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

If you work with Word a lot, you probably use styles. If you use styles a lot, you've probably balled your fist more often than not when working with the ribbon. In Word 2007/2010, one of the things that I find missing when using styles is a quic…
Shortcuts in Word Just the other day I had a training for Microsoft and they wanted me to show how well the new Windows and Office behaved on a touch device, which by the way is great, but it was only then that I realized that using keyboard shortc…
This video walks the viewer through the process of creating Hyperlinks for the web and other documents. Select the "Insert" tab: Click "Hyperlink":  Type "http://" followed by a web address to reference a website or navigate to a document to ref…
Learn how to make your own table of contents in Microsoft Word using paragraph styles and the automatic table of contents tool. We'll be using the paragraph styles in Word’s Home toolbar to help you create a table of contents. Type out your initial …

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now