Visual Basic Programming Code Examples
Visual Basic > Applications VBA Code Examples
How to Parse Out a Path
How to Parse Out a Path
The following class module will take a path such as 'C:\vb\projects\pathparse\cfileparse.cls' and parse out the different elements. Just assign the path to the FullPath property and then read the properties for Drive, Path, Filename, and Extension.
Create a New class module and insert this code
Option Explicit
Private msFullPath As String
Private msPath As String
Private msDrive As String
Private msFile As String
Private msExt As String
Public Property Get FullPath() As String
FullPath = msFullPath
End Property
Public Property Let FullPath(sNewFullPath As String)
Dim iPos As Integer
Dim iCounter As Integer
msFullPath = sNewFullPath
msDrive = ""
msPath = ""
msFile = ""
msExt = ""
'Get the Drive
iPos = InStr(1, msFullPath, ":")
If iPos > 0 Then 'Drive exists
msDrive = Left$(msFullPath, iPos)
End If
If Right$(msFullPath, 1) = "/" Or _
Right$(msFullPath, 1) = "\" Or _
InStr(1, msFullPath, ".") = 0 Then
'No file specified in this path
msFile = ""
msExt = ""
msPath = msFullPath
'Append a backslash if one does not exist
If Right$(msPath, 1) <> "/" And _
Right$(msPath, 1) <> "\" Then
msPath = msPath & "\"
End If
Else
iPos = Len(msFullPath)
'Loop backwards through msFullPath _
'until we have all of the filename
For iCounter = iPos To 1 Step -1
If Mid$(msFullPath, iCounter, 1) = "/" _
Or Mid$(msFullPath, iCounter, 1) = "\" Then
'No more characters for the file
Exit For
Else
msFile = Mid$(msFullPath, _
iCounter, 1) & msFile
End If
Next
'Parse out the path without the filename
msPath = Left$(msFullPath, _
Len(msFullPath) - Len(msFile))
'Get the extension
iPos = InStr(1, msFile, ".")
msExt = Right$(msFile, Len(msFile) - iPos)
End If
End Property
Public Property Get Path() As String
Path = msPath
End Property
Public Property Get Drive() As String
Drive = msDrive
End Property
Public Property Get File() As String
File = msFile
End Property
Public Property Get Extension() As String
Extension = msExt
End Property