簡體   English   中英

將共享文件夾路徑轉換為 ​​UNC 路徑

[英]Convert Shared folder path to UNC path

我正在嘗試通過使用計算機名稱操作當前路徑來將當前共享文件夾路徑轉換為 ​​unc 路徑。 但是導致編譯錯誤:公共函數 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

我剛剛發現並修改了這個,歸功於它,是遲到的:

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

我很驚訝這一行沒有拋出 Mismatch 錯誤:

CurrentPathA = Split(CurrentPath, "\")

Split函數將字符串轉換為數組。 因此,嘗試將Split的結果分配給字符串變量應該會引發錯誤。

在任何情況下, Ubound函數都需要一個數組。 因此,當您執行Ubound(_string_)而不是UBound(_array_)時會出現錯誤。

Dim CurrentPathA As Variant

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM