Relative instead of Absolute paths in Excel VBA

前端 未结 8 932
眼角桃花
眼角桃花 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:44

    if current directory of the operating system is the path of the workbook you are using, Workbooks.Open FileName:= "TRICATEndurance Summary.html" would suffice. if you are making calculations with the path, you can refer to current directory as . and then \ to tell the file is in that dir, and in case you have to change the os's current directory to your workbook's path, you can use ChDrive and ChDir to do so.

    ChDrive ThisWorkbook.Path
    ChDir ThisWorkbook.Path
    Workbooks.Open FileName:= ".\TRICATEndurance Summary.html"
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题