none
File Name and Path Macro RRS feed

  • Question

  • I would like to create a macro which will insert the filename and path into every Word document and I want to edit the font size etc.  I have tried this by inserting the field codes for this, but can't find a way to edit the font (and it appears bold also).  I am okay with recording a macro, but a bit at sea with footers and the best way to do this.  Also myy christian name appears in the file path - can I change this to my initials only?  Many thanks.
    Sunday, February 19, 2012 6:13 PM

Answers

  • This illustrates the dangers of grabbing code from somewhere without understanding how it works or what it's intended to do.

    First, both of these macros should do the same thing, so you need only one of them.

    The first one, which mentions Building Blocks.dotx, inserts a building block entry that really consists of just the FILENAME field. There are two problems with this approach: first, that it depends on the existence of a Building Blocks.dotx template in the folder path shown in the macro (and evidently you aren't Josephine, so that path doesn't exist on your computer); and second, that the template must contain a building block named FileNameandPathFooter, which it probably doesn't contain unless you created it.

    The second macro is safer because it doesn't depend on any external conditions that might not be there. It just creates the FILENAME field directly. But it has a couple of problems for what you want to do. First, it inserts the field wherever the cursor happens to be at the time you start the macro, and that could be in the middle of the document's text. Second, the \* Lower switch makes the displayed path and name all lower case, which you may or may not want. Third, there's nothing in the macro that would make the field show 8pt bold.

    Knowing these things, it's possible to rewrite the second macro to fix the problems:

    Sub FileNameandPathFooter()
        Dim fld As Field
        With ActiveDocument
            Set fld = .Fields.Add( _
                Range:=.Sections(1).Footers(wdHeaderFooterPrimary).Range, _
                Type:=wdFieldEmpty, _
                Text:="FILENAME \p \* CHARFORMAT", _
                PreserveFormatting:=False)
            fld.Code.Font.Size = 8
            fld.Code.Bold = True
            fld.Update
        End With
    End Sub

    The Range argument is now set to the primary footer of the first section of the document. If your document uses "Different first page" or "Different odd and even", you'll need additional statements to put the same footer on those pages. If there are later sections whose footers are unlinked (Same As Previous turned off), you'll also need to add the footer to those sections. Finally, this macro will replace any existing footer, so if that's the case in your documents, you'll have to adjust the Range argument to point to exactly where you want it.

    The \* CHARFORMAT switch replaces the \* MERGEFORMAT switch that gets inserted when PreserveFormatting is True; and PreserveFormatting is now set to False.

    There are additional statements to set the formatting to 8pt bold, and the Update statement makes the formatting take effect.


    Jay Freedman
    MS Word MVP  FAQ: http://word.mvps.org

    • Marked as answer by Bruce Song Friday, March 2, 2012 2:25 AM
    Tuesday, February 21, 2012 3:31 PM
  • Hi Josephine,

    The presence of your name in the path is because that's the user-account name your profile was created with. If you're not seeing your initials instead of your name with my macro, that's because you haven't configured Word with them and/or the same name as in your user-account. Since you've said elsewhere that you're using Office 2010 (http://social.technet.microsoft.com/Forums/en-US/word/thread/6cde8be8-2614-4b4f-8ec4-358e6a7fabcd) you do that in Word via File|Options > General. Once you've done that, to get the 'Docs' filepath change you asked about, replace:
    Str = Doc.Path & "\"
    Str = Replace(Str, "\", "\\")
    Inits = Trim(Application.UserInitials)
    If Inits = "" Then Inits = "..."
    Str = Replace(Str, Application.UserName, Inits)
    with:
    Str = Application.UserInitials & "\\Docs\\"

    As for date & time insertion, Word offers a number of fields - DATE, CREATEDATE, PRINTDATE and SAVEDATE. The field for:
    • DATE can be used to display today's date & time and to update them each time the document is opened/printed;
    • CREATEDATE can be used to display the date & time the document was created or last saved using Save As;
    • PRINTDATE can be used to display the date & time the document was last printed;
    • SAVEDATE can be used to display the date & time the document was last saved;
    A wide variety of display formats is supported. You can insert any of these fields via Insert|Quick Parts|Field.


    Cheers
    Paul Edstein
    [MS MVP - Word]

    • Marked as answer by Bruce Song Friday, March 2, 2012 2:25 AM
    Thursday, February 23, 2012 9:55 AM

All replies

  • If your only concern is with the formatting of the field, that can be easily taken care of. Just apply the formatting you want (which is most easily done by applying a style to the paragraph in which the field resides).

    Stefan Blom, Microsoft Word MVP
    Sunday, February 19, 2012 7:12 PM
  • Or you could use the Charformat switch.

    Cheers
    Paul Edstein
    [MS MVP - Word]

    Sunday, February 19, 2012 9:51 PM
  • True.

    Stefan Blom, Microsoft Word MVP
    Sunday, February 19, 2012 10:07 PM
  • Many thanks - I now keep getting a message of runtime error - collection can't be found etc.  Last time I had this, someone was kind (and clever) enough to create a macro for me to use, since mine kept on coming up with the same error message.  I honestly haven't heard of Charformat!
    Monday, February 20, 2012 4:56 PM
  • Many thanks - I now keep getting a message of runtime error - collection can't be found etc.  Last time I had this, someone was kind (and clever) enough to create a macro for me to use, since mine kept on coming up with the same error message.  I honestly haven't heard of Charformat!

      

      

    Please show us the code you are using.

    For what it's worth, \* CHARFORMAT is a switch that you can add to the FILENAME field code. It doesn't require any coding.


    Stefan Blom, Microsoft Word MVP

    Monday, February 20, 2012 6:28 PM
  •  Sub FileNameandPath()
    '
    ' FileNameandPath Macro
    '
    '
        Application.Templates( _
            "C:\Users\Josephine\AppData\Roaming\Microsoft\Document Building Blocks\1033\14\Building Blocks.dotx" _
            ).BuildingBlockEntries("FileNameandPathFooter").Insert Where:=Selection. _
            Range, RichText:=True
    End Sub
    Sub FileNameandPathFooter()
    '
    ' FileNameandPathFooter Macro
    '
    '
        Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, Text:= _
            "FILENAME  \* Lower \p ", PreserveFormatting:=True
    End Sub

    You can see I have been getting into a mess but probably also see what I have been trying to do.  I cannot find a way to make this footer appear at the bottom of the page, nor get the font to 8pt and not bold. I wondered also if there is a way to get rid of the 'josephine' on the file path as I can't find where this originated.  Many thanks.

     
    Tuesday, February 21, 2012 1:42 PM
  • This illustrates the dangers of grabbing code from somewhere without understanding how it works or what it's intended to do.

    First, both of these macros should do the same thing, so you need only one of them.

    The first one, which mentions Building Blocks.dotx, inserts a building block entry that really consists of just the FILENAME field. There are two problems with this approach: first, that it depends on the existence of a Building Blocks.dotx template in the folder path shown in the macro (and evidently you aren't Josephine, so that path doesn't exist on your computer); and second, that the template must contain a building block named FileNameandPathFooter, which it probably doesn't contain unless you created it.

    The second macro is safer because it doesn't depend on any external conditions that might not be there. It just creates the FILENAME field directly. But it has a couple of problems for what you want to do. First, it inserts the field wherever the cursor happens to be at the time you start the macro, and that could be in the middle of the document's text. Second, the \* Lower switch makes the displayed path and name all lower case, which you may or may not want. Third, there's nothing in the macro that would make the field show 8pt bold.

    Knowing these things, it's possible to rewrite the second macro to fix the problems:

    Sub FileNameandPathFooter()
        Dim fld As Field
        With ActiveDocument
            Set fld = .Fields.Add( _
                Range:=.Sections(1).Footers(wdHeaderFooterPrimary).Range, _
                Type:=wdFieldEmpty, _
                Text:="FILENAME \p \* CHARFORMAT", _
                PreserveFormatting:=False)
            fld.Code.Font.Size = 8
            fld.Code.Bold = True
            fld.Update
        End With
    End Sub

    The Range argument is now set to the primary footer of the first section of the document. If your document uses "Different first page" or "Different odd and even", you'll need additional statements to put the same footer on those pages. If there are later sections whose footers are unlinked (Same As Previous turned off), you'll also need to add the footer to those sections. Finally, this macro will replace any existing footer, so if that's the case in your documents, you'll have to adjust the Range argument to point to exactly where you want it.

    The \* CHARFORMAT switch replaces the \* MERGEFORMAT switch that gets inserted when PreserveFormatting is True; and PreserveFormatting is now set to False.

    There are additional statements to set the formatting to 8pt bold, and the Update statement makes the formatting take effect.


    Jay Freedman
    MS Word MVP  FAQ: http://word.mvps.org

    • Marked as answer by Bruce Song Friday, March 2, 2012 2:25 AM
    Tuesday, February 21, 2012 3:31 PM
  • All of that can be done without the need for a macro, by simply inserting the FILENAME field into the template's footer, with the field coded as:
    {FILENAME \p \* Charformat}
    and formatting at least the 'F' with the required font.

    What it doesn't do is to address the OP's request for the path to display the user's initials instead of their name. That can't be done with a FILENAME field. For that, you'd need a macro along the lines of:

    Sub FileNameandPathFooter()
    Application.ScreenUpdating = False
    Dim Doc As Document, Rng As Range, Fld As Field, Str As String, Inits As String
    Set Doc = ActiveDocument
    With Doc.Sections(1).Footers(wdHeaderFooterPrimary)
      Set Rng = .Range.Characters.First
      Rng.Collapse
      For Each Fld In .Range.Fields
        With Fld
          If InStr(.Code, "QUOTE") Then
            If .Code.Fields.Count > 0 Then
              If .Code.Fields(1).Type = wdFieldFileName Then
                Set Rng = Fld.Result
                .Delete
                Exit For
              End If
            End If
          End If
        End With
      Next
      Str = Doc.Path & "\"
      Str = Replace(Str, "\", "\\")
      Inits = Trim(Application.UserInitials)
      If Inits = "" Then Inits = "..."
      Str = Replace(Str, Application.UserName, Inits)
      Set Fld = Doc.Fields.Add(Range:=Rng, Type:=wdFieldQuote, _
        Text:="""" & Str & "¶" & """ \* Charformat", PreserveFormatting:=False)
      With Fld
        Set Rng = .Code.Duplicate
        Rng.MoveStartUntil "¶", wdForward
        Rng.MoveEndUntil "¶", wdBackward
        With Doc
          .ActiveWindow.View.ShowFieldCodes = True
          .Fields.Add Range:=Rng, Type:=wdFieldFileName, PreserveFormatting:=False
          .ActiveWindow.View.ShowFieldCodes = False
        End With
        .Code.Font.Size = 8
        .Code.Bold = True
        .Update
      End With
    End With
    Set Doc = Nothing: Set Fld = Nothing
    Application.ScreenUpdating = True
    End Sub

    The reason I've kept this in a QUOTE field with an embedded FILENAME field is to make it easier to ID and update later.


    Cheers
    Paul Edstein
    [MS MVP - Word]

    Wednesday, February 22, 2012 3:16 AM
  • I have tried both of the above.  The first works perfectly and being short, I understand it more.  You are both quite right that I haven't got 'under the bonnet (hood)' knowledge and just want to press the right buttons!  Am I right in assuming the one written by Paul has variables in it which I am supposed to fill in before it will work?  The perfect footer for me would be c:\users\jmk\docs\filename - at present it is

    C:\Users\Josephine\Documents\filename, which is rather long, although now in 8 pt and not bold.  I am not sure where or how to make these changes and would very much appeciate one more go for me to copy intact.  Sorry if this is not what you do here, but it is the most help I can find from the most knowledgeable!  Many thanks for the help so far anyway.

    Wednesday, February 22, 2012 3:00 PM
  • Am I right in assuming the one written by Paul has variables in it which I am supposed to fill in before it will work?

    No.

    The perfect footer for me would be c:\users\jmk\docs\filename.

    That's what my macro does. Getting there - in a way that can be updated in the path or filename changes - is a whole lot more complicated than simply inserting a FILENAME field - which is all Jay's macro does, and which you don't need a macro of any kind for.


    Cheers
    Paul Edstein
    [MS MVP - Word]


    • Edited by macropodMVP Wednesday, February 22, 2012 9:14 PM
    Wednesday, February 22, 2012 9:12 PM
  • Yes, both do the same now, ie C:\User\Josephine\Documents\file name. I see in Paul's macro there does seem to be a variable for my initials (jmk) or is this just another example of my not understanding code. Can documents be shortened to 'docs'? Actually I have hunted high and low to trace where the 'josephine' is coming from and whether I can change it, but no such luck, ie have changed computer name, user account etc.  I used to be a master of Wordperfect, but am determined to persevere with Word which has many great features (although why not an option for filename and path along with signature, date and time insertion.....
    Thursday, February 23, 2012 9:24 AM
  • Hi Josephine,

    The presence of your name in the path is because that's the user-account name your profile was created with. If you're not seeing your initials instead of your name with my macro, that's because you haven't configured Word with them and/or the same name as in your user-account. Since you've said elsewhere that you're using Office 2010 (http://social.technet.microsoft.com/Forums/en-US/word/thread/6cde8be8-2614-4b4f-8ec4-358e6a7fabcd) you do that in Word via File|Options > General. Once you've done that, to get the 'Docs' filepath change you asked about, replace:
    Str = Doc.Path & "\"
    Str = Replace(Str, "\", "\\")
    Inits = Trim(Application.UserInitials)
    If Inits = "" Then Inits = "..."
    Str = Replace(Str, Application.UserName, Inits)
    with:
    Str = Application.UserInitials & "\\Docs\\"

    As for date & time insertion, Word offers a number of fields - DATE, CREATEDATE, PRINTDATE and SAVEDATE. The field for:
    • DATE can be used to display today's date & time and to update them each time the document is opened/printed;
    • CREATEDATE can be used to display the date & time the document was created or last saved using Save As;
    • PRINTDATE can be used to display the date & time the document was last printed;
    • SAVEDATE can be used to display the date & time the document was last saved;
    A wide variety of display formats is supported. You can insert any of these fields via Insert|Quick Parts|Field.


    Cheers
    Paul Edstein
    [MS MVP - Word]

    • Marked as answer by Bruce Song Friday, March 2, 2012 2:25 AM
    Thursday, February 23, 2012 9:55 AM
  • Almost there - I have copied the above and now have just initials, docs, file name, but now all footers end with doc.x after the file name, so probably there is something I have to remove.  Many thanks for all this help, I will copy these macros in a safe place for any future use.  As regards date, time etc, I just meant that as these are provided with one click in the ribbon, then it is a pity the same was not available for filename and path.

    Josephine

    Thursday, February 23, 2012 11:40 AM
  • Hi Josephine,

    The docx extension is part of the filename. If you don't want that, use this code instead:

    Sub FileNameandPathFooter()
    Application.ScreenUpdating = False
    Dim Doc As Document, Rng As Range, Fld As Field, Str As String
    Set Doc = ActiveDocument
    With Doc.Sections(1).Footers(wdHeaderFooterPrimary)
      Set Rng = .Range.Characters.First
      Rng.Collapse
      For Each Fld In .Range.Fields
        With Fld
          If InStr(.Code, "QUOTE") Then
            Set Rng = Fld.Result
            .Delete
            Exit For
          End If
        End With
      Next
      Str = Mid(Doc.Path, InStr(Doc.Path, "Documents\"), Len(Doc.Path))
      Str = Replace(Str, "Documents\", "\Docs\") & "\"
      Str = Application.UserInitials & Replace(Str, "\", "\\") & Doc.Name
      Set Fld = Doc.Fields.Add(Range:=Rng, Type:=wdFieldQuote, _
        Text:="""" & Str & """ \* Charformat", PreserveFormatting:=False)
      With Fld
        .Code.Font.Size = 8
        .Code.Bold = True
        .Update
      End With
    End With
    Set Doc = Nothing: Set Fld = Nothing
    Application.ScreenUpdating = True
    End Sub

    This code, though much shorter than before, is slightly enhanced over the last mods I suggested, in that it also tracks the sub-folder names under your Documents folder.


    Cheers
    Paul Edstein
    [MS MVP - Word]

    Thursday, February 23, 2012 12:00 PM
  • Copied and pasted that one, but it comes up with Runtime Error 5 - Invalid Procedure Call or Argument.  I see I have two End Subs - is that the problem?

    Jo

    Thursday, February 23, 2012 12:18 PM
  • Copied and pasted that one, but it comes up with Runtime Error 5 - Invalid Procedure Call or Argument.  I see I have two End Subs - is that the problem?


    Definitely a problem - you'll see that my code only has one.

    Cheers
    Paul Edstein
    [MS MVP - Word]

    Thursday, February 23, 2012 9:14 PM
  • Everything fine now and I have the macro of my dreams at last.  Just my initials, placement of file and name of file without an extension, all in a tiny line at the bottom of documents.  I have even made hard copies of all this, just in case as you have gone to so much trouble and I wouldn't like to have to ask you again!  Many, many thanks.

    Jo

    Friday, February 24, 2012 9:26 AM