VBA – Word: Dokumentenstruktur reparieren / Navigation Pane Document Structure Fix [Update (2014-04-03)]

Auch wenn es naheliegend ist mit Hilfe des Inhaltsverzeichnisses durch ein Word-Dokument zu navigieren, falls es denn ein Inhaltsverzeichnis gibt, bietet sich dafür doch auch die Dokumentenstruktur an.

Deutsche Beschreibung (Fortsetzung)

Die Dokumentenstruktur bietet den Vorteil, dass sie beim Bearbeiten eines Textes einfacher anzuwenden ist, um zu bestimmten Punkten im Dokument zu springen. Hinzu kommt, dass beim Erstellen eines Dokumentes das Inhaltsverzeichnis evtl. noch gar nicht existiert oder nicht (immer) aktuell ist.

Auch wenn die Dokumentenstruktur sehr hilfreich ist, gibt es mit ihr doch leider immer wieder Probleme. Probleme treten z.B. vermehrt auf, wenn man ein mit Word 2003 erstelltes Dokument in Word 2007 öffnet, dann sieht die Dokumentenstruktur mitunter gar nicht mehr strukturiert aus. Aber nicht nur durch das verwenden einer anderen Word-Version kann die Anzeige der Dokumentenstruktur beeinträchtigt werden. In solchen Fällen, wenn die Dokumentenstruktur nicht mehr korrekt angezeigt wird, hilft das folgende Makro weiter, dass die Dokumentenstruktur neu aufbaut.

Update 1: Ich habe eine neue Variante zum Reparieren der Dokumentenstruktur hinzugefügt. Diese arbeitet deutlich schneller als die alte. Der Ansatz ist allerdings auch ein anderer.

Ein generelles Problem scheint aber sowohl bei der neuen, als auch bei der alten Variante zu bestehen: Die Dokumentenstruktur ist bei erneutem Öffnen des Dokuments wieder defekt. Der Grund hierfür ist anscheinend ein automatisierter Mechanismus in Word (siehe hierzu auch die folgende Seite von Microsoft Problembehandlung bei der Dokumentenstruktur), der – für den Fall, dass auf den ersten paar Seiten kein Inhaltsverzeichnis oder ein Text, der mit einer der Standard-Überschriftenformatvorlage formatiert wurde, gefunden wird – automatisch nach dem Öffnen versucht, anhand des Erscheinungsbildes von Absätzen, Gliederungsebenen zuzuweisen und so die Dokumentenstruktur aufzubauen. Leider funktioniert letzteres nicht wirklich gut. Wenn die korrigierte Dokumentenstruktur erhalten bleiben soll, ein Inhaltsverzeichnis allerdings (noch) nicht existiert, oder das Inhaltsverzeichnis zu weit hinten ist, kann man das automatische Neuaufbauen der Dokumentenstruktur durch drücken von Esc beim Öffnen der Datei abbrechen.

Update 2: Mit beiden Makrovarianten kann es unter bestimmten Umständen zu Problemen (ungewollten Ergebnissen) kommen. Für genauere Informationen sollte der folgende Beitrag auf MS Office 2007 – Hilfe angeschaut werden: Dokumentstruktur wird nicht angezeigt (da die Seite mittlerweile nicht mehr existiert, verweist der Link jetzt auf die entsprechende Seite von https://archive.org).

Update 3 (2010-11-03): Am einfachsten kann man das Problem komplett umgehen, indem die Dokumentenstruktur beim Laden des jeweiligen Dokuments deaktiviert ist. Wartet man dann so lange, bis Word das Dokument vollständig geladen hat (das ist nicht der Fall, sobald es angezeigt wird, es dauert noch einen Moment) und schaltet erst dann die Dokumentenstruktur ein, wird sie korrekt dargestellt. Dieses Vorgehen ist meiner Meinung nach die einfachste und beste Lösung.

Bei dem unter Update 2 erwähnten Beitrag wird angesprochen, dass die “neue Variante” (Möglichkeit 2) des Makros die Gliederungsebene „ohne Rücksicht auf Verluste“ ändert. Schaut man sich diese im jeweiligen Optionsfenster in Word allerdings an, sieht man, dass die Gliederungsebene nicht immer zu ändern ist, sondern bei Standardformatvorlagen, wie z.B. Überschriften, ausgegraut und nicht änderbar ist.

Update 4 (2014-04-03): Jetzt auch mit englischer Übersetzung der Beschreibung und englischen Kommentaren im Sourcecode.

English version of the description

It’s obvious to navigate through a Word document with help of a table of contents (if it exists), but the Navigation Pane lends itself for using. The Navigation Pane offers you the advantage of easier jumping to headings in the document during document creation and document editing. In addition, during document creation the table of contents may not even exist or not (always) is up to date.

Even if the Navigation Pane is very helpful, from time to time it doesn’t work correct. For example: Problems occur increasingly when you open a document created with Word 2003 in Word 2007. Then sometimes the Navigation Pane doesn’t look like the table of contents anymore. But the document structure shown in the Navigaten Pane also can be affected by other reasons. In such cases, if the document structure in the Navigation Pane is not shown correctly, the following macro helps rebuilding the shown structure.

Update 1: I added a new version of the macro. This works much faster than the old one. But the approach is also different.

However a general problem seems to exist in both versions: The shown document structure in the Navigation Pane is defective when opening the document again. The reason for this is apparently an automated mechanism in Word (see also the following Microsoft site Problembehandlung bei der Dokumentenstruktur (only german version)). This mechanism automatically attempt after opening in case that on the first few document pages no table of contents or a text formatted with one of the default heading styles was found. 
The mechanism tries to allocate outline levels and to build up the document structure based on the appearance of paragraphs. Unfortunately, this functionality does not really work well. In case that the shown document structure in the Navigation Pane is correct, but a table of contents not (yet) exist or the table of contents is not part of the first document pages, you can stop the automatic rebuilding of the Navigation Pane document structure by pressing Esc while opening the file.

Update 2: Both macro variants may lead to problems (unwanted results) under certain circumstances. For more detailed information, the following forum thread of „MS Office 2007 – Hilfe“ should viewed: Dokumentstruktur wird nicht angezeigt (only german) (as the website is not available anymore, the link refers to the according website of https://archive.org).

Update 3 (2010-11-03): The easiest way to avoid the problem completely, is to disable the Navigation Pane during loading of the document. Then you can open the document and must wait until Word fully loaded the document (which is not the case, when it appears, it takes a moment longer). After the document has been loaded completely you can activate the Navigation Pane again. Now the document structure in the Navigation Pane should be shown correctly. This approach is in my opinion the easiest and best solution.
In the forum thread mentioned under Update 2 the following point is addresed: Variant 2 (new version) of the macro changes the the outline level „without regard to losses.“ If you look at this in the respective option window in Word, you can see that the outline level cannot be changed in any case. This option is blocked (grayed out and not changeable) for standard styles, such as Headings.

Update 4 (2014-04-03): English translation of the description added. Source code comments translated to english.

Sourcecode

Variante 1 (alte Version) / Variant 1 (old version)

Public Sub DokumentenstrukturReparieren()
    ' In case of errors goto jump point NoDocumentOpen and end function.
    On Error GoTo NoDocumentOpen

    ' If no file is open, goto jump point NoDocumentOpen and end funtion. The check if a file is open is done with help of the filename length of the active document.
    If Len(ActiveDocument.Name) = 0 Then GoTo NoDocumentOpen

    Dim bEbene As Byte
    Dim lPos As Long
    Dim bTrackRev As Boolean
    Dim bDocMap As Boolean

    ' Turn of screen updating
    Application.ScreenUpdating = False ' Screen updating on (true) or off (false). If screen updating is turned off, all operations, which result in screen updates, should be done faster. Please note that some function do not work correct anymore if the screen updating is turned off (e.g. print). You should always keep in mind that the screen updating needs to be re-enabled if it has been previously disabled.

    With ActiveWindow
        ' safe current state of document structure
        bDocMap = .DocumentMap ' The display state of the document structure (shown or hidden) of the active window is safed in bDocMap.
        ' Dokumentenstruktur anzeigen
        .DocumentMap = True ' With help of ActiveWindow.DocumentMap the display state of the active window can be changed: Shown (true) and Hidden (false).
    End With

    With ActiveDocument
        ' safe current state of revision tracking
        bTrackRev = .TrackRevisions ' The current state of the revision tracking of the active window is stored in bTrackRev.
        ' Turn off Revision Tracking
        .TrackRevisions = False ' With ActiveDocument.TrackRevisions the display state of the revision tracking of the active document can be changed: Shown (true) and hodden (false).

        With Selection
            ' The following searrch is done for outline levels 1 to 9.
            For bEbene = 1 To 9
                ' goto beginning of document
                .HomeKey(Unit:=wdStory)

                ' set of search parameters for outline level
                With .Find
                    .ClearFormatting()
                    .Replacement.ClearFormatting()
                    .Text = ""
                    .Replacement.Text = ""
                    .Forward = True
                    .Wrap = wdFindContinue
                    .Format = True
                    .MatchCase = False
                    .MatchWholeWord = False
                    .MatchWildcards = False
                    .MatchSoundsLike = False
                    .MatchAllWordForms = False
                    .ParagraphFormat.OutlineLevel = bEbene
                End With

                ' initialization of search position
                lPos = -1
                ' do search for the whole document with all outline levels
                Do While .Find.Execute And .Start <> lPos
                    ' Set oultine level to 'Body Text'
                    .ParagraphFormat.OutlineLevel = wdOutlineLevelBodyText
                    ' update search position
                    lPos = .Start ' set current position as new start position.
                    ' updated marked area to document area to be searched
                    .Collapse(Direction:=wdCollapseEnd)
                Loop
            Next bEbene

            ' reset oultine level settings of search parameters
            .Find.ParagraphFormat.OutlineLevel = wdOutlineLevelBodyText ' set outline level for search to "Body Text".
        End With

        ' reset state of document structure
        ActiveWindow.DocumentMap = bDocMap
        ' reset display state of revision tracking
        .TrackRevisions = bTrackRev
    End With

NoDocumentOpen:
    ' turn on screen updating
    Application.ScreenUpdating = True
End Sub

Variante 2 (neue Version) / Variant 2 (new version)

Diese Lösung wurde mir von einem Bekannten empfohlen, da sie deutlich schneller ist. Ich konnte zwar selbst noch keine negativen Auswirkungen auf meine Dokumente feststellen, habe diese Variante aber auch noch nicht so ausgiebig getestet.

English: This solution was recommended to me by a friend as it is much faster. I could not find any negative effects on my documents, but I did not test this variant extensively.

Public Sub DokumentenstrukturReparieren()
    ' In case of errors goto jump point NoDocumentOpen and end function.
    On Error GoTo NoDocumentOpen

    ' If no file is open, goto jump point NoDocumentOpen and end funtion. The check if a file is open is done with help of the filename length of the active document.
    If Len(ActiveDocument.Name) = 0 Then GoTo NoDocumentOpen

    ' Turn of screen updating
    Application.ScreenUpdating = False      ' Screen updating on (true) or off (false). If screen updating is turned off, all operations, which result in screen updates, should be done faster. Please note that some function do not work correct anymore if the screen updating is turned off (e.g. print). You should always keep in mind that the screen updating needs to be re-enabled if it has been previously disabled.

    ' select complete document
    Selection.WholeStory()
    ' Set oultine level to 'Body Text'
    Selection.ParagraphFormat.OutlineLevel = wdOutlineLevelBodyText     ' Here the oultine level of the selected text will be set to "Body Text". Outline levels, which are set incorrect (the real problem in case of a wrong document structure in the Navigation Pane), will be treated as normale text. Headings keep the predefined outline levels.

NoDocumentOpen:
    ' turn on screen updating
    Application.ScreenUpdating = True
End Sub