Reputation: 152
the following code is part of a much bigger piece of work (where it all works exactly as I wanted except this part). I have a field in the footer with the document name and this takes the .doc/.docx off the end. The problem is that it appears that this code also updates any links within the body of the document with the name of the document also e.g. if a link in the document is www.google.co.uk this macro will change that link on the document to the name of the document - I want this to only happen in the footer.
Can you please advise on how to get this code to do that? I have tried a few different things but none of them work.
oldFilename = wdDocTgt.Name
If Right(oldFilename, 5) = ".docx" Then
oldFilename = Left(oldFilename, Len(oldFilename) - 5)
ElseIf Right(oldFilename, 4) = ".doc" Then
oldFilename = Left(oldFilename, Len(oldFilename) - 4)
' MsgBox (oldFilename) 'UNCOMMENT TO TEST
'Updates all fields in the target document with the file name
For Each aStory In wdDocTgt.StoryRanges
For Each aField In aStory.Fields
aField.Result.Text = oldFilename
Next aField
Next aStory
Upvotes: 0
Views: 189
Reputation: 25663
The problem with your code is that it's addressing all parts of the document - which you don't want. You want only the footer(s). A Word document can have many footers, depending on how many sections the document has and whether the footers in the sections have been unlinked from previous sections. So if you wanted to check all the footers, you'd need to loop all the sections, something like
Dim sec as Word.Section
Dim rngFooter as Word.Range
For each sec in ActiveDocument.Sections
Set rngFooter = sec.Footers(wdHeaderFooterPrimary).Range
For each field in rngFooter.Fields
aField.Result.Text = oldFilename
Next field
Next sec
But keep in mind this will address all fields in the Footers, so it would end up affecting any Page numbers or Dates you might have...
There's another issue with the approach you're using: Field codes will update, and when they do, anything you've written to them, as you do in your code, will be lost. So you might be in for a very unpleasant surprise when you print this document, or when some other action triggers a field code update.
Since you aren't relying on the field code to generate the document name automatically, don't use a field code (whatever it might be). Delete the field code and use a bookmark, instead. Then you can assign the document name to the bookmark, something like this:
Dim rngBkm as Word.Range
Dim sBkmName as String
sBkmName = "DocName"
If ActiveDocument.Bookmarks.Exists(sBkmName) Then
Set rngBkm = ActiveDocument.Bookmarks(sBkmName)
rngBkm.Text = oldFileName
'Assigning the text deletes the bookmark, so add it back
ActiveDocument.Bookmarks.Add sBkmName, rngBkm
End If
Note: I do NOT recommend you use the suggestion in Comments to open the Footer - no need to actually OPEN it and better not to.
Upvotes: 1