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

时间:2015-02-25 15:25:56

标签: excel vba compiler-errors

我尝试通过使用计算机名操作当前路径来将当前共享文件夹路径转换为unc路径。但是导致编译错误:行上的预期数组" elem = UBound(CurrentPathA)"在公共函数UNCpath()中。你们能告诉我导致这个问题的问题吗?并且可能会分享更好的想法来获取路径?

    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

2 个答案:

答案 0 :(得分:6)

或者使用文件系统对象:

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

我刚刚发现并修改了信用证到期的,这是迟到的:

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

答案 1 :(得分:2)

我很惊讶这条线不会引发Mismatch错误:

CurrentPathA = Split(CurrentPath, "\")

Split函数将字符串转换为数组。因此,尝试将Split的结果分配给字符串变量应该会引发错误。

在任何情况下,Ubound函数都需要一个数组。因此,当您执行Ubound(_string_)而不是UBound(_array_)时出现错误。

Dim CurrentPathA As Variant