PDA

View Full Version : Problem inserting a field into a paragraph



hoggm2
01-13-2016, 09:09 AM
I have a large number of documents to update to a consistent style and brand. This will involve changing headers, footers, and front page. I am trying to do this with a separate .dotm file which holds the common information in bookmarks, and then use a macro to update each document when it is opened.

I am using a macro to insert the INCLUDETEXT field. It works reliably in the header and footer, but not in the body of the document. For diagnostics, I have stripped back the code to determine what is going on.

What I have discovered is that if the document is completely blank, the field is inserted correctly into the first paragraph. However, if paragraphs are present the document has the information inserted but without the curly brackets. I.e. it is not a field.

I am obviously doing something wrong, but I cannot see what is causing this. Some expert opinions would be greatly appreciated. I have exhausted my ability to diagnose further.


Sub addText()


Dim BMRange As Range
Dim includeText As String
Dim Filename As String


Filename = "FILENAME \p"


includeText = "INCLUDETEXT " + """" + Filename + " \ " + " \ " + styleFileName + """" + " "


Set BMRange = ActiveDocument.Paragraphs(1).Range
With BMRange
.Text = includeText
End With
fInsertFields BMRange, includeText

Set BMRange = ActiveDocument.Sections(1).Headers(wdHeaderFooterPrimary).Range
With BMRange
.Text = includeText
End With
fInsertFields BMRange, includeText


End Sub






Public Sub fInsertFields(oRng As Range, Optional searchText As String)
With oRng
'Find the expression and add a field around it
With .Find
.Text = searchText
.MatchCase = True
While .Execute
oRng.Fields.Add oRng, wdFieldEmpty, , False
oRng.Collapse wdCollapseEnd
Wend
End With
End With
lbl_Exit:
Exit Sub
End Sub


This first shot is what I expect to see, and what I get if I start with a blank document.

15164


This is a document I start with (by way of example) that gives me a problem

15165


This is the result where the field is not entered in the body, but is in the header.


15166



Thanks in anticipation.


Regards

Martin

gmayor
01-13-2016, 10:30 PM
Why insert an empty field? Insert a filename field. The following will replace the first paragraph content with a filename field.:
Dim oRng As Range
Set oRng = ActiveDocument.Paragraphs(1).Range
oRng.End = oRng.End - 1
ActiveDocument.Fields.Add Range:=oRng, Type:=wdFieldFileName, Text:="\p", PreserveFormatting:=False