如何为映射到不同驱动器的两个人编写文件路径

时间:2019-01-25 21:00:51

标签: excel vba

我正在尝试编写仅将某些用户保存时将excel电子表格备份保存到同一共享文件夹(映射到两个不同字母)的代码。这是一个可供许多人访问的文件,所以我只想在我或我的同事在其中时保存备份。

我已将文件夹映射到G驱动器,我的同事将其保存在I驱动器上。如何写文件路径来读取两个驱动器?

TIA!

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
    If Environ("Username") <> "agene" And Environ("Username") <> "aking" Then
        Exit Sub
    End If
    With ThisWorkbook
        .SaveCopyAs ("\Excel\Backup\Backup of " & .Name)
    End With
End Sub

1 个答案:

答案 0 :(得分:0)

网络路径很棘手。我根据另一位作者的工作为自己的库创建了一个函数,以确定给定驱动器号的网络驱动器的标准路径名。因此,请为每个用户获取驱动器号,确定完整的网络路径,并始终使用该网络路径来保存文件。

Public Function GetNetworkPath(ByVal driveName As String) As String
    '--- Converts a drive letter, e.g. 'W:\', to its fully qualified network
    '    path useful for saving a network folder location without any user-
    '    specific custom mapping
    '--- from https://www.mrexcel.com/forum/excel-questions/
    '            658830-show-full-file-paths-unc-not-mapped-drive-letters-print.html
    Dim networkObject  As Object
    Dim networkDrives As Object

    Set networkObject = CreateObject("WScript.Network")
    Set networkDrives = networkObject.enumnetworkdrives

    Dim i As Long
    GetNetworkPath = vbNullString
    For i = 0 To networkDrives.count - 1 Step 2
        If UCase$(networkDrives.item(i)) = UCase$(driveName) Then
            GetNetworkPath = networkDrives.item(i + 1)
            Exit For
        End If
    Next
End Function