如何在VBA中获取当前工作表的路径?

问题描述 投票:0回答:6

我编写了一个宏作为加载项,我需要获取正在执行该宏的当前工作表的路径。我该怎么做?如何获取文件路径(只是目录)?

excel vba
6个回答
344
投票

仅使用

Application.ActiveWorkbook.Path
表示路径本身(不带工作簿名称),或使用
Application.ActiveWorkbook.FullName
表示带有工作簿名称的路径。


41
投票

总是很高兴拥有:

Dim myPath As String     
Dim folderPath As String 

folderPath = Application.ActiveWorkbook.Path    
myPath = Application.ActiveWorkbook.FullName

37
投票

如果您想从执行宏的位置获取工作簿的路径 - 使用

Application.ThisWorkbook.Path

Application.ActiveWorkbook.Path
有时会产生意想不到的结果(例如,如果您的宏在多个工作簿之间切换)。


4
投票

最快的方法

path = ThisWorkbook.Path & "\"

0
投票

我遇到了同样的问题,我构建了一个我将分享的解决方案。下面是 Excel 的 VBA 函数 GetLocalPath(),它获取 ActiveWorkbook 的本地路径:

`函数 GetLocalPath() 作为字符串

Dim sRowPath    As String
Dim sLocalPath  As String
Dim iFindhttp   As Integer

sRowPath = Application.ActiveWorkbook.Path

If LCase(Left(sRowPath, 4)) = "http" Then
    Dim fso As New FileSystemObject
    sLocalPath = fso.GetAbsolutePathName(sRowPath)
    iFindhttp = InStr(LCase(sLocalPath), "\http")
    sLocalPath = Left(sLocalPath, iFindhttp - 1)
    Set fso = Nothing
Else
    sLocalPath = sRowPath
End If
        
GetLocalPath = sLocalPath

结束功能`


0
投票

获取工作表路径的最准确方法是 (假设您有 ws 作为工作表):

ws.Parent.Path

© www.soinside.com 2019 - 2024. All rights reserved.