Excel

Insert Filename and X Folder Levels in Header or Footer

Ease of Use

Easy

Version tested with

2002 

Submitted by:

Zack Barresse

Description:

Set the header or footer to display the filename and a specified number of subsequent folders from the file. 

Discussion:

As files add up on some computer's, and in an attempt at becoming more organized with their data files, it's sometimes needed to create multiple folders in which to separate and store your files. 

Code:

instructions for use

			

Option Explicit Private Sub Workbook_BeforePrint(Cancel As Boolean) Dim fname As String, str As String, i As Long, myLen As Long, _ cnt As Long, sname As String, myset As String fname = ActiveWorkbook.FullName sname = ActiveWorkbook.Name myLen = Len(fname) 'full length of path and filename, used to step through ' each character and check for folder seperator "\" cnt = 0 On Error GoTo lessThanAmt 'Errors out if the number you set below does not ' get met before the iteration is fully completed For i = myLen To 1 Step -1 If cnt > 2 Then 'Set number for how many folders deep you want to see str = Right(fname, myLen - i + 1) Exit For 'Exit when a match is found End If 'Before match is met, check each character with Mid Function If Mid(fname, i - 1, 1) = "\" Then cnt = cnt + 1 End If Next i If str <> "" Then str = ".." & Left(str, Len(str) - Len(ActiveWorkbook.Name)) & sname End If With ActiveSheet.PageSetup 'Set Font, Font Attribute and Font Size here if you'd like myset = "&""Tahoma,Italic""&10" .RightFooter = myset & str End With Exit Sub lessThanAmt: With ActiveSheet.PageSetup 'Set Font, Font Attribute and Font Size here if you'd like myset = "&""Tahoma,Italic""&10" 'Make the footer default to the Full Path on errors .RightFooter = myset & fname End With Err.Clear End Sub

How to use:

  1. From Excel, hit Alt + F11.
  2. From the VBE menu select your file on left.
  3. Ensure 'Microsoft Excel Objects' is expanded.
  4. Double click on 'ThisWorkbook'.
  5. Copy/Paste code into right pane.
  6. Go through commented code (green) and change where dictated appropriate; noted as such.
  7. Press Alt + Q
  8. Save file before running.
 

Test the code:

  1. Ensure any necessary changes have been made to the code.
  2. Click File -> Print Preview.
  3. Check Header/Footer for File Path (partial) and FileName.
 

Sample File:

FooterPathEx.zip 10KB 

Approved by mdmackillop


This entry has been viewed 115 times.

Please read our Legal Information and Privacy Policy
Copyright @2004 - 2020 VBA Express