2017-07-31 56 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")通常更容易。