Trim/Split Filename and insert as text field

R

Reiner Griess

Hi there,

hopefully you guys guide me... Im not familiar with VB.

I want to add the filename of a special format in the footer of a word
doc, automatically everytime I save the doc.

This is what I want in detail:

1. When file gets saved
- set file name (document property) to the name of the file, trimmed
down to the characters before the first underscore (_).

E.g. Filename is "myfile_sometxt.doc" -> will get "myfile"

2. Automatically set the filename variable (trimmed down in step 1) into
the footer of the document.


Any help would be reaaaally appreciated.
Tank you!
reiner

PS: This is what I've done so far...

Macro to get the trimmed down filename:
Sub InsertFnameOnly()
Dim fname, fname2 As String
ActiveDocument.Save
fname2 = Selection.Document.Name
fname = Left(fname2, (InStr(fname2, "_") - 1))
Selection.TypeText fname
End Sub

Problems:
- how to set the filename in document properties?
- how to paste the trimmed filename into the footer?
- how to do this automatically (ie without the need of explicitely
execute any macro)?
 
J

Jezebel

1. Create a Custom document property called eg FileShortName. (Use File >
Properties > Custom. Give the property any value you like.)

2. In the footer of the document, insert a DocProperty field: { DocProperty
FileShortName }

3. Write a macro called something like SetName:

Private Sub SetName()

Dim pName as string
Dim pIndex as long
Dim pDialog as Word.Dialog

set pDialog = Dialogs(wdDialogFileSaveAs)

'Show the dialog without carrying out any actions
'(returns TRUE if user clicks OK)
If pDialog.Display then
pName = pDialog.Name
pIndex = instr(pName, "_")

'User might not enter a name with an underscore
if pIndex > 0 then
pName = left$(pName, pIndex - 1)
end if

'Set the property
ActiveDocument.CustomDocumentProperties("FileShortName") = pName

'Update fields in the footer. Might need to change this if you have
a first page footer, or multiple sections, etc
ActiveDocument.Sections(1).Footers(wdHeaderFooterPrimary).Range.Fields.Update

'Save the document under the new name
pDialog.Execute
end if

End Sub

4. Write a macro called FileSaveAs to run in place of the built-in SaveAs
command. All this macro does is call SetName.

5. Write a macro called FileSave. This calls SetName only if the document
has never been saved; otherwise it simply saves the document.
 
R

Reiner Griess

Hey Jezebel,

simply greeeeat!

I thank you *very* much for this 100% and *fast* answer.

Wow, that was fast!

Yours, scincerely
reiner
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top