如何从Application.Path获取UNC路径?

问题描述 投票:4回答:3

我想在vba代码中获取活动工作簿的路径。 ActiveWorkbook.Path这样做

我需要它来检索这样的东西:

\\MachineName\ShareFolder\ETC\ETC2

不:

S:\ETC\ETC2

S:映射到\\MachineName\ShareFolder\的地方。我该怎么办?

vba
3个回答
1
投票
    Dim Drive As String
    Drive = Left(ActiveWorkbook.Path, 2)

    ActiveWorkbookPath = Replace(ActiveWorkbook.Path, Drive, GetNetworkPath(Drive))


Function GetNetworkPath(ByVal DriveName As String) As String

    Dim objNtWork  As Object
    Dim objDrives  As Object
    Dim lngLoop    As Long


    Set objNtWork = CreateObject("WScript.Network")
    Set objDrives = objNtWork.enumnetworkdrives

    For lngLoop = 0 To objDrives.Count - 1 Step 2
        If UCase(objDrives.Item(lngLoop)) = UCase(DriveName) Then
            GetNetworkPath = objDrives.Item(lngLoop + 1)
            Exit For
        End If
    Next

End Function

1
投票

在尝试转换文件路径或任何类似垃圾之前,请尝试Workbook对象提供的其他几个属性。我个人使用ActiveWorkbook.FullName与我的所有项目(托管在网络驱动器上),我从来没有遇到过问题。

也就是说,如果这种方法不起作用,那么肯定有转换文件路径的方法。虽然我更喜欢首先浏览对象的属性(它们往往更可靠),但我不能使用函数来解决问题。这是查看这篇文章的地方:https://pagecommunication.co.uk/2014/07/15/vba-to-convert-a-mapped-drive-letter-to-unc-path/并检查这个答案Convert Shared folder path to UNC path可能会有所帮助。两者之间的唯一区别是前者需要引用Microsoft.Scripting.Runtime,而另一个则不需要。


-1
投票

下面的代码将以您请求的方式标识文件路径。

Path = Right(CurDir(), Len(CurDir()) - InStr(CurDir(), "\") + 1)
© www.soinside.com 2019 - 2024. All rights reserved.