excel - 将共享文件夹路径转换为 ​​UNC 路径

标签 excel vba compiler-errors

我正在尝试通过使用计算机名称操作当前路径将当前共享文件夹路径转换为 ​​unc 路径。但是会导致编译错误:公共(public)函数 UNCpath() 中的“elem = UBound(CurrentPathA)”行上存在预期数组。你们能告诉我造成这个问题的原因是什么吗?也许分享更好的想法来获取 unc 路径?

    Option Explicit

    #If VBA7 Then
    Private Declare PtrSafe Function fnGetComputerName Lib "kernel32" Alias "GetComputerNameW" (ByVal lpBuffer As LongPtr, ByRef nSize As Long) As Long
    #Else
    Private Declare Function fnGetComputerName Lib "kernel32" Alias "GetComputerNameW" (ByVal lpBuffer As Long, ByRef nSize As Long) As Long
    #End If

    Public Function GetComputerName() As String
    Const MAX_COMPUTERNAME_LENGTH As Long = 31

    Dim buf As String, buf_len As Long

    buf = String$(MAX_COMPUTERNAME_LENGTH + 1, 0)
    buf_len = Len(buf)

    If (fnGetComputerName(StrPtr(buf), buf_len)) = 0 Then
    GetComputerName = "ErrorGettingComputerName"
    Else
    GetComputerName = Left$(buf, buf_len)
    End If
    End Function


    Public Function UNCpath() As String
    Dim CompName As String, CurrentPath As String, CurrentPathA As String

    CompName = GetComputerName()
    CurrentPath = ThisWorkbook.Path
    CurrentPathA = Split(CurrentPath, "\")
    elem = UBound(CurrentPathA)
    CurrentPath = CurrentPathA(elem)
    UNCpath = "\\" & CompName & "\" & CurrentPath
    End Function

最佳答案

或者使用文件系统对象:

Function GetUNCLateBound(strMappedDrive As String) As String

    Dim objFso  As Object
    Set objFso = CreateObject("Scripting.FileSystemObject")

    Dim strDrive As String
    Dim strShare As String

    'Separate the mapped letter from
    'any following sub-folders
    strDrive = objFso.GetDriveName(strMappedDrive)

    'find the UNC share name from the mapped letter
    strShare = objFso.Drives(strDrive & "\").ShareName

    'The Replace function allows for sub-folders
    'of the mapped drive
    GetUNCLateBound = Replace(strMappedDrive, strDrive, strShare)

    Set objFso = Nothing 'Destroy the object

End Function

我刚刚发现并修改了此内容,应予延迟绑定(bind):

http://pagecommunication.co.uk/2014/07/vba-to-convert-a-mapped-drive-letter-to-unc-path/

关于excel - 将共享文件夹路径转换为 ​​UNC 路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28722852/

相关文章:

ruby-on-rails - 每次都与SASS非法嵌套

vba - Excel 工作表触发器和事件

ms-access - 如何在VBA中创建IsMissingOrEmptyString来处理可选参数?

vba - 如何引用不同工作表上同名的图表?

c++ - 安装新的 g++ 后无法编译

xcode - 错误 : main. jsbundle 不存在 - React Native 0.60.4

python - 在Python中有一个元组列表,对于每个元组,希望将x[0]和x[1]放入Excel电子表格的A列和B列中

vba - 如何在VBA中动态创建的ComboBox上创建Sub?

excel - VBA从特定位置的数组中删除项目

vba - 为什么这个 VBA 生成的 QR 码会卡顿? (仅限条形码-vba-宏)