2017-07-31 39 views
1

我为自己和同事创建了一个门户网站,用于下载参考不同网络驱动器以合并的工作簿模板。为不同用户返回VBA网络驱动器号

门户位于“Accounting”(Z:/)驱动器中,但其中一个工作簿在另一个驱动器“BI”(Y:/)中引用电子表格。

这在我的机器上出色地工作,但我的同事有不同的驱动器字母(例如M:/ Accounting,U:/ BI)。

有没有办法在网络中搜索名称并返回驱动器号?

这里是我的代码粗略的估计:

Option Explicit 

Sub mySub() 


dim WBaPath as String 
dim WBbPath as String 
WBaPath = "Y:\BI-Accounting\myWorkbook.xlsm" 
WBbPath = "Z:\Portal\myOtherWorkbook.xlsm" 
dim WBa as Workbook 
dim WBb as Workbook 
set WBa = Workbooks.open(WBaPath) 
set WBb = ThisWorkbook 

'Code to do stuff 


End Sub 

的文件夹和文件将具有相同的名称,但什么是确保在我的部门中的所有用户都可以使用这些工具而无需最好的办法重新编程,最好不必在运行时选择?

+3

使用[UNC路径](https://en.wikipedia.org/wiki/Path_(computing)#Uniform_Naming_Convention)而不是驱动器号。 –

回答

2

可以使用FileSystemObject's Drives property来实现这一点:

Function FindDriveLetter(shareToFind As String) As String 
    Dim fs As Object 
    Dim dc As Object 
    Dim d As Object 
    Set fs = CreateObject("Scripting.FileSystemObject") 
    Set dc = fs.Drives 
    For Each d In dc 
     If d.drivetype = 3 Then 
      If UCase(d.sharename) = UCase(shareToFind) Then 
       FindDriveLetter = d.driveletter 
       Exit Function 
      End If 
     End If 
    Next 
    FindDriveLetter = "" 
End Function 

Sub Test() 
    MsgBox FindDriveLetter("\\SERVER01\SHAREXYZ\FILES") 
    ' use whatever share name you have mapped to your "Y" or "Z" drive 
    ' instead of "\\SERVER01\SHAREXYZ\FILES" 
End Sub 

但是使用UNC路径(例如WBaPath = "\\SERVER01\SHAREXYZ\FILES\BI-Accounting\myWorkbook.xlsm")通常更容易。