This can be achieved with an event handler in a global template (add-in).
Create a new document and save it as a macro-enabled template (*.dotm) file, temporarily in your Templates folder.
Open the macro editor, and insert a module and a class module. Using the Properties pane, rename the module as AppEvents and rename the class module as ThisApplication.
In the module, paste this code:
Dim oAppClass As New ThisApplication
Public Sub AutoExec()
Set oAppClass.oApp = Word.Application
End Sub
In the class module, paste this code:
Public WithEvents oApp As Word.Application
Private Sub oApp_DocumentBeforeClose(ByVal Doc As Document, Cancel As Boolean)
With ActiveDocument
If .Type <> wdTypeDocument _
Or .BuiltInDocumentProperties(wdPropertyTitle) = .Name _
Then Exit Sub
If .Path = "" Then
.BuiltInDocumentProperties(wdPropertyTitle) = .Range.Sentences(1)
Else
.BuiltInDocumentProperties(wdPropertyTitle) = .Name
End If
.Saved = False ' force a save
End With
End Sub
Then save the template, and copy it to the folder %appdata%\Microsoft\Word\Startup. Templates stored in that folder are global; they are loaded whenever Word starts up. Restart Word to make the code active.
When you create a new document (and presumably save it one or more times while working on it), the Title property will be empty. When you close the document or shut down Word, the code in the add-in will run. If the Title has already been changed to the file's
name, the code will do nothing. If the document has never been saved, the .Path will be empty, so the Title will be set to the first sentence (Word doesn't really know what a "line" is!). If the file has been saved before, but the Title is different from the
file name, then the Title will be changed to the file name and the document will be saved again.
_____________________________
https://jay-freedman.info
1 person found this reply helpful
·
Was this reply helpful?
Sorry this didn't help.
Great! Thanks for your feedback.
How satisfied are you with this reply?
Thanks for your feedback, it helps us improve the site.
How satisfied are you with this reply?
Thanks for your feedback.