Multiple Apps

Get the File Name or the Path

Ease of Use

Easy

Version tested with

2000, 2002 

Submitted by:

Justinlabenne

Description:

Function that returns the file name or the path from a given Full Name 

Discussion:

This function uses a files full name (Path and Name) and extracts either the path, or the file name based on what is specified for the second argument. The first argument takes the Files full name, the second arguement uses an Enumeration for easier specifying of what to return (the file name or path) Note: This code is tested for Word & Excel only! 

Code:

instructions for use

			

Option Explicit 'Enumeration for what to return Public Enum PathReturn GetPath = 1 GetFile = 0 End Enum Public Function StripFileOrPath(FullPath As String, _ ReturnType As PathReturn) As String ' ===================================================================== ' Returns either the FileName or the Path from a given Full FileName ' 1st Arg = Pass a files full name (C:\Example\MyFile.xls) ' 2nd Arg = What to return (either the file name or the path ' Enumerated for easier selection ' ===================================================================== Dim szPathSep As String szPathSep = Application.PathSeparator Dim szCut As String szCut = CStr(Empty) Dim i As Long i = Len(FullPath) Dim szPath As String Dim szFile As String If i > 0 Then Do While szCut <> szPathSep szCut = Mid$(FullPath, i, 1) If szCut = szPathSep Then szPath = Left$(FullPath, i) szFile = Right$(FullPath, Len(FullPath) - i) End If i = i - 1 Loop Select Case ReturnType Case GetPath StripFileOrPath = szPath Case GetFile StripFileOrPath = szFile End Select Else StripFileOrPath = CStr(Empty) End If End Function Sub TestItForExcel() ' Test for Excel MsgBox StripFileOrPath(ThisWorkbook.FullName, GetFile) MsgBox StripFileOrPath(ThisWorkbook.FullName, GetPath) End Sub

How to use:

  1. Open an Excel Workbook
  2. Copy the code
  3. Press Alt + F11 to open the Visual Basic Editor (VBE)
  4. Select INSERT > MODULE from the menubar
  5. Paste code into the right pane
  6. Press Alt+Q to return to Excel
  7. Save workbook before any other changes
 

Test the code:

  1. Go to TOOLS > MACRO > MACROS
  2. When the dialog appears, select (TestIt)
  3. Press Run
 

Sample File:

GetFilesOrPath Examples.zip 16.18KB 

Approved by mdmackillop


This entry has been viewed 128 times.

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