我编写了一个宏作为加载项,我需要获取正在执行该宏的当前工作表的路径。我该怎么做?如何获取文件路径(只是目录)?
仅使用
Application.ActiveWorkbook.Path
表示路径本身(不带工作簿名称),或使用 Application.ActiveWorkbook.FullName
表示带有工作簿名称的路径。
总是很高兴拥有:
Dim myPath As String
Dim folderPath As String
folderPath = Application.ActiveWorkbook.Path
myPath = Application.ActiveWorkbook.FullName
如果您想从执行宏的位置获取工作簿的路径 - 使用
Application.ThisWorkbook.Path
Application.ActiveWorkbook.Path
有时会产生意想不到的结果(例如,如果您的宏在多个工作簿之间切换)。
最快的方法
path = ThisWorkbook.Path & "\"
我遇到了同样的问题,我构建了一个我将分享的解决方案。下面是 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
结束功能`
获取工作表路径的最准确方法是 (假设您有 ws 作为工作表):
ws.Parent.Path