【问题标题】:Go up one folder level上一层文件夹
【发布时间】:2020-10-31 08:05:14
【问题描述】:

我有一个获取子文件夹数据的宏。但是我也想要主文件夹中的一些东西。

我查看了How to get current working directory using vba?,但需要更改活动工作簿路径:

Application.ActiveWorkbook.Path might be "c:\parent\subfolder"

我想要

"c:\parent\"

使用 Excel 365 VBA

【问题讨论】:

    标签: vba excel


    【解决方案1】:

    由于路径可能不是当前工作目录,您需要从字符串中提取路径。

    找到最后一个\ 并读取左侧的所有字符:

    ParentPath = Left$(Path, InStrRev(Path, "\"))
    

    如果你在当前目录下工作,ChDir ".." 会让你上一级,CurrDir 可以返回新路径。

    【讨论】:

    • 我应该说它总是在工作目录中(在这种情况下!)。但很高兴知道!
    • 试试这样:Left$(application.ActiveWorkbook.Path, InStrRev(application.ActiveWorkbook.Path, "\")-1)
    • 谢谢。发现我也会尽早将代码放在一行! (在主代码上)
    【解决方案2】:

    最可靠的方法是使用 Scripting.FileSystemObject。它有一个方法可以在不尝试解析的情况下获取父文件夹:

    With CreateObject("Scripting.FileSystemObject")
        Debug.Print .GetParentFolderName(Application.ActiveWorkbook.Path)
    End With
    

    【讨论】:

      【解决方案3】:
      Dim WbDir As String
      Dim OneLvlUpDir As String
      
      'get current WorkBook directory
      WbDir = Application.ActiveWorkbook.Path
      
      'get directory one level up
      ChDir WbDir
      ChDir ".."
      
      'print new working directory and save as string. Use as needed.
      Debug.Print CurDir()
      OneLvlUpDir = CurDir()
      

      【讨论】:

        【解决方案4】:

        我认为你的意思是这个解决方案:

        Sub t()
        Dim fso As Object
        Set fso = CreateObject("Scripting.FileSystemObject")
        MsgBox "ThisWorkbook.Path = " & ThisWorkbook.Path & vbLf & _
        "Path one folder down = " & fso.GetFolder(ThisWorkbook.Path & "\." & "NewFolder").Path
        Set fso = Nothing
        End Sub
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-12-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多