Relative instead of Absolute paths in Excel VBA

前端 未结 8 936
眼角桃花
眼角桃花 2020-12-05 04:10

I have written an Excel VBA macro which imports data from a HTML file (stored locally) before performing calculations on the data.

At the moment the HTML file is ref

8条回答
  •  醉梦人生
    2020-12-05 04:48

    Here's my quick and simple function for getting the absolute path from a relative path.

    The difference from the accepted answer is that this function can handle relative paths that moves up to parent folders.

    Example:

    Workbooks.Open FileName:=GetAbsolutePath("..\..\TRICATEndurance Summary.html")
    

    Code:

    ' Gets an absolute path from a relative path in the active workbook
    Public Function GetAbsolutePath(relativePath As String) As String
        
        Dim absPath As String
        Dim pos As Integer
        
        absPath = ActiveWorkbook.Path
        
        ' Make sure paths are in correct format
        relativePath = Replace(relativePath, "/", "\")
        absPath = Replace(absPath, "/", "\")
        
        Do While Left$(relativePath, 3) = "..\"
        
            ' Remove level from relative path
            relativePath = Mid$(relativePath, 4)
            
            ' Remove level from absolute path
            pos = InStrRev(absPath, "\")
            absPath = Left$(absPath, pos - 1)
        
        Loop
        
        GetAbsolutePath = PathCombine(absPath, relativePath)
        
    End Function
    

提交回复
热议问题