PDA

View Full Version : Code to change header



chris9104
09-08-2016, 03:25 AM
This is a section of code in a larger piece, but this section changes the header


If DrpHead.Value = "York" Then
ActiveDocument.ActiveWindow.View.SeekView = wdSeekCurrentPageHeader
Selection.WholeStory
Selection.Delete
ActiveWindow.ActivePane.View.SeekView = wdSeekMainDocument
If ActiveWindow.View.SplitSpecial <> wdPaneNone Then
ActiveWindow.Panes(2).Close
End If
If ActiveWindow.ActivePane.View.Type = wdNormalView Or ActiveWindow. _
ActivePane.View.Type = wdOutlineView Then
ActiveWindow.ActivePane.View.Type = wdPrintView
End If
ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageHeader
Application.Templates( _
"C:\Users\Chris\AppData\Roaming\Microsoft\Document Building Blocks\1033\15\Building Blocks.dotx" _
).BuildingBlockEntries("York").Insert Where:=Selection.Range, RichText:= _
True
ActiveWindow.ActivePane.View.SeekView = wdSeekMainDocument
End If

Keep getting an error on the section about choosing the application template, it works fine if I have manually added a header while the file is open, but errors if I run it without the manual change of header.
17049

gmayor
09-08-2016, 04:17 AM
You don't have to select the header in order to write to it, but you must specify which header(s) you wish to process; however the error message appears to suggest that you are looking in the wrong place for the building block.


Dim oRng As Range
Dim strTemplate As String
Dim strBBName As String
strTemplate = Environ("APPDATA") & _
"\Microsoft\Document Building Blocks\1033\" & _
val(Application.Version) & _
"\Building Blocks.dotx"
strBBName = "York"
Set oRng = ActiveDocument.Sections(1).Headers(wdHeaderFooterPrimary).Range
oRng.Text = ""
Application.Templates(strTemplate). _
BuildingBlockEntries(strBBName).Insert _
Where:=oRng, _
RichText:=True

The building block should be ideally stored in the template containing the macro (though by default it is likely to have been stored in the normal template). Move it to the document template and then change strTemplate to

strTemplate = ThisDocument.FullNameto reflect the template the macro is in.

If you want to find the building block wherever it is stored - see http://www.gmayor.com/word_vba_examples_3.htm

gmaxey
09-08-2016, 12:05 PM
You can also explicit insert BBs using Gallery/Category/Name

oTmp.BuildingBlockTypes(wdTypeAutoText).Categories("General").BuildingBlocks("New Entry").Insert Where:=Selection.Range, RichText:=True