Changing path to parent directory of active working folder

北城余情 提交于 2019-12-25 11:54:34

问题


I have a code that is list files in directory. how can I address code to look into parent directory of current workbook directory? i want it to be independent wherever I place it. (first code addressing to the second one to read file from) Thanks.

....
      Application.ScreenUpdating = False
      ShowPDFs "C:\Test\Working\", ws
        ws.UsedRange.EntireColumn.AutoFit
    Application.ScreenUpdating = True
End Sub
------------------------------
Private Sub ShowPDFs(ByRef fsoPath.......

回答1:


Just check that the file is not at root level:

....
    Application.ScreenUpdating = False

        ShowPDFs ThisWorkbook.Path & "\..", ws

        ws.UsedRange.EntireColumn.AutoFit

    Application.ScreenUpdating = True

End Sub
------------------------------
Private Sub ShowPDFs(ByRef fsoPath.......



回答2:


The solution you want:

If your behavior is to open an excel window and then open your recent file, please note that you should not forget to add change Drive and then change Directory into your VBA code.

Cause the Excel always start with the default Directory even it's just open your recent file !

Then, these should be help.

Solution A: You don't need to get parent directory to do anything else.

Dim ThisWorkbookPath As String
Dim ThisWorkbookPathParts As Variant

ThisWorkbookPath = ThisWorkbook.Path
ThisWorkbookPathParts = Split(ThisWorkbookPath, _
                        Application.PathSeparator)

ChDrive ThisWorkbookPathParts(LBound(ThisWorkbookPathParts))
ChDir ThisWorkbookPath

Solution B: You may need to get parent directory to do things else.

Dim ParentPath As String: ParentPath = "\"
Dim ThisWorkbookPath As String
Dim ThisWorkbookPathParts, Part As Variant
Dim Count, Parts As Long

ThisWorkbookPath = ThisWorkbook.Path
ThisWorkbookPathParts = Split(ThisWorkbookPath, _
                        Application.PathSeparator)

Parts = UBound(ThisWorkbookPathParts)
Count = 0
For Each Part In ThisWorkbookPathParts
    If Count > 0 Then
        ParentPath = ParentPath & Part & "\"
    End If
    Count = Count + 1
    If Count = Parts Then Exit For
Next

MsgBox "File-Drive = " & ThisWorkbookPathParts _
       (LBound(ThisWorkbookPathParts))
MsgBox "Parent-Path = " & ParentPath


来源:https://stackoverflow.com/questions/46919941/changing-path-to-parent-directory-of-active-working-folder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!