Extract File or Path

By | 2019-09-29

Extract either a filename or path from a fully qualified pathname.

Module

Option Explicit

Public Function ParsePath(strFullPathName As String, ReturnType As Integer, Optional StripLastBackslash) As String
'
' Returns: Either the path or filename of a fully qualified pathname.
' See below for details.
'
' Called with:
' strFullPathName - STRING (REQUIRED) - the full path and file name of interest
' If strFullPathName has a length of zero, ParsePath returns a string of zero length.
' ReturnType - INTEGER (REQUIRED) - must be one of:
' vbDirectory (16) - returns the directory part of strFullPathName
' vbNormal (0) - returns the filename part of strFullPathName
' Anything else returns the full path name, which means that nothing really happens...
' StripLastBackslash - VARIANT(Boolean) (OPTIONAL) - TRUE to remove the last backslash,
' FALSE to leave it. Defaults to FALSE. Assumes that TRUE returns -1, and FALSE
' returns 0.
'
' Dependencies: None
'
'
    Dim strTemp As String, intX As Integer, strPathName As String, strFileName As String

    If IsMissing(StripLastBackslash) Then StripLastBackslash = False
    If Len(strFullPathName) > 0 Then
        strTemp = ""
        intX = Len(strFullPathName)
        Do While strTemp <> "\"
            strTemp = Mid(strFullPathName, intX, 1)
            If strTemp = "\" Then
                strPathName = Left(strFullPathName, intX + StripLastBackslash)
                strFileName = Right(strFullPathName, Len(strFullPathName) - intX)
            End If
            intX = intX - 1
        Loop

        Select Case ReturnType
        Case vbDirectory
            ParsePath = strPathName
        Case vbNormal
            ParsePath = strFileName
        Case Else
            ParsePath = strFullPathName
            ' As an alternative, you could do
            ' ParsePath = ""
        End Select
    Else
    ' You should never end up here, but if the pathname passed is
    ' a zero-length string you will, so...
        ParsePath = ""
    End If

End Function

Usage

Option Explicit

Private Sub Command1_Click()
    MsgBox ParsePath("c:\windows\calc.exe", vbDirectory, True)
End Sub

Author: dwirch

Derek Wirch is a seasoned IT professional with an impressive career dating back to 1986. He brings a wealth of knowledge and hands-on experience that is invaluable to those embarking on their journey in the tech industry.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.