Generate a Relative Path Between Folders

Generate a Relative Path Between Folders

You can use a Shell Light Weight API to generate a relative path by using this code:

 Private Declare Function PathRelativePathToW _Lib "shlwapi.dll" (ByVal pszPath As Long, _ByVal pszFrom As Long, ByVal dwAttrFrom As _Long, ByVal pszTo As Long, ByVal dwAttrTo _As Long) As BooleanPrivate Function GetRelativePath( _sRelativePath As String, ByVal sPathFrom _As String, ByVal sPathTo As String) As _BooleanDim bResult As BooleanConst MAX_PATH As Long = 260sRelativePath = Space(MAX_PATH)' Set "dwAttr..." to vbDirectory for' directories, 0 for filesbResult = PathRelativePathToW(StrPtr _(sRelativePath), StrPtr(sPathFrom), _vbDirectory, StrPtr(sPathTo), 0)If bResult ThensRelativePath = Left(sRelativePath, _InStr(sRelativePath, vbNullChar) - 1)ElsesRelativePath = ""End IfGetRelativePath = bResultEnd FunctionPrivate Sub Command1_Click()Dim sRelative As String' txtFromPath should contain the directory' path to go from, txtToPath should contain' the file path to go to.' txtRelativePath will contain the resultIf GetRelativePath(sRelative, _txtFromPath.Text, txtToPath.Text) ThentxtRelativePath.Text = sRelativeElsetxtRelativePath.Text = "Error"End IfEnd Sub

PathRelativePathTo requires shlwapi.dll version 4.71 or higher, which ships with Internet Explorer 4. See for versioning details.


Share the Post: