Forum Discussion
Lance_Kester
May 03, 2022Copper Contributor
Making a document number appear in several places
Hi
I've created a Word template and used a macro to insert a document number which increases sequentially each time a new document is created from the template. This works fine, but I need to make the number appear in several places in the document. The macro inserts the number inside a bookmark in the new document, however if I try to use a cross-reference the number won't appear in the other locations. Any ideas on how to overcome this would be welcome!
Many thanks
Lance
The macro I've used is below:
Sub AutoNew()
Dim MyString, docNumber
FileToOpen = "c:\Users\lance\docNumfile.txt"
Open FileToOpen For Input As #1
Input #1, docNumber
Close #1 ' Close file
Dim BMRange As Range
'Identify current Bookmark range and insert text
Set BMRange = ActiveDocument.Bookmarks("docNum").Range
BMRange.Text = docNumber
docNumber = docNumber + 1
'Re-insert the bookmark
ActiveDocument.Bookmarks.Add "docNum", BMRange
Open FileToOpen For Output As #1
Write #1, docNumber
Close #1 ' Close file.
End Sub
4 Replies
Sort By
- Instead of using a bookmark have your code assign the number to a document variable by using the code below to set the value of the variable and update the fields in the document, and where ever you want the number to appear in the document, insert a { DOCVARIABLE DocNum } field.
With ActiveDocument
.Variables("DocNum").Value = docnumber
.Range.Fields.Update
End With- Lance_KesterCopper Contributor
Doug_Robbins_Word_MVP Many thanks for the prompt reply Doug. The code and field work fine in the document, but I can't get the DOCVARIABLE field to work if it's embedded in the header. Is there any way of doing this?
Regards
Lance Kester
Use
Dim i as Long, j as Long
With ActiveDocument
.Variables("DocNum").Value = docnumber
.Range.Fields.Update
For i = 1 to .Sections.CountWith Sections(i)
For j = 1 to .Headers.Count
.Headers(j).Range.Fields.UpdateNext j
End With
Next i
End With