VB and VBA Users Source Code: Returning the parent folder of a path
[
Home
|
Contents
|
Search
|
Reply
| Previous | Next ]
VB/VBA Source Code
Returning the parent folder of a path
By:
Andrew Baker
Email (spam proof):
Email the originator of this post
Date:
Wednesday, August 31, 2005
Hits:
4829
Category:
Files/Directories/IO
Article:
The code below returns the parent folder name given a path. A demonstration routine can be found at the bottom of this post. 'Purpose : Returns a specified parent folder given a path. 'Inputs : sFolder The folder to return the parent folder of. ' [lParentIndex] The index of the parent to return (1 returns the parent, 2 returns the grand parent etc). 'Outputs : Returns the requested parent folder. 'Author : Andrew Baker 'Date : 25/03/2005 'Notes : Public Function PathGetParent(ByVal sFolder As String, Optional lParentIndex As Long = 1) As String Dim asFolders() As String Dim sPathSep As String Dim lThisFolder As Long If Len(sFolder) > 0 Then 'Determine the path seperator If InStr(1, sFolder, "/") > 0 Then sPathSep = "/" Else sPathSep = "\" End If If Right$(sFolder, 1) <> sPathSep Then sFolder = sFolder & sPathSep End If asFolders = Split(sFolder, sPathSep) 'Get the requested parent folder For lThisFolder = 0 To UBound(asFolders) - lParentIndex - 1 PathGetParent = PathGetParent & asFolders(lThisFolder) & sPathSep Next End If End Function 'Demo routine Sub Test() Debug.Print PathGetParent("C:\Andrew\Test") Debug.Print PathGetParent("C:\Andrew\Test", 2) Debug.Print PathGetParent("http://www.vbusers.com/code/") End Sub
Terms and Conditions
Support this site
Download a trial version of the Excel Workbook Rebuilder