2014-03-05 145 views
0

Excel工作簿,我維持中有這樣VBA代碼:爲什麼驅動器號在Excel 2010中使此VBA代碼失敗?

Function GetDrivePath(DriveLetter As String) As String 
Dim DrivePath As String 
Dim DriveLen As Long 

'DrivePath = Space(260) 
DriveLen = Len(DrivePath) 

If WNetGetConnection(DriveLetter, DrivePath, DriveLen) = error_success Then 
    GetDrivePath = DrivePath 
Else 
    GetDrivePath = DriveLetter 
End If 
End Function 

直到最近這段代碼工作正常,但現在失敗。即使在Excel工作表的存檔版本中,它也不再有效。

如果這個格式的路徑在Excel工作簿中使用,這不叫:

\\servername\filepath 

但它被調用時路徑具有驅動器號:

X:\filepath 

現在它失敗時,它叫做。它從未有過這個問題。

代碼應該返回驅動器號引用的服務器路徑。

它返回的錯誤並不特別有用;這是一個簡單的類型不匹配錯誤。


典型輸入:

X: 

其中 「X」 是一個驅動器字母。

典型輸出:

\\servername\path-to-folder-that-X-is-mapped-to 

聲明語句:

Declare Function WNetGetConnection Lib "mpr.dll" Alias "WNetGetConnectionA" (ByVal lpszLocalName As String, ByVal lpszRemoteName As String, cbRemoteName As Long) As Long 
+0

WNetGetConnection是做什麼的?你能告訴我們那個代碼嗎? – aphoria

+0

@aphoria它是一個微軟功能。 – called2voyage

+0

這裏是關於它的[Microsoft的信息](http://msdn.microsoft.com/en-us/library/windows/desktop/aa385453(v = vs.85).aspx)。 – called2voyage

回答

0

原來,這個問題其實並不在此代碼依賴於庫中,但在不同的參考。

Office 2007中有一個名爲Office 2010中已不存在這種控制仍在在VBA代碼引用對話框中引用Microsoft日曆控件控制,即類似於但不完全是這樣的:

Missing control

要解決這個問題,我進入VBA代碼查看器,打開工具下拉菜單並單擊引用。這會產生類似於上述的對話框。我只是取消選中缺少的引用(甚至沒有在此excel工作簿中使用),然後單擊確定。這立即清除了所有問題。

值得注意的是,它甚至與原來的代碼一起工作,據說這是錯誤的。

3

我知道你說的是用來工作的,但我沒有看到你發佈的代碼怎麼可能有曾經工作過。

試試這個...這個假定error_success被定義爲一個全局變量或常量。

變量DrivePath必須預先格式化爲完整的空格字符串,否則WNetGetConnection無法使用它返回UNC路徑。

Public Function GetDrivePath(DriveLetter As String) As String 
    Dim DrivePath As String 
    Dim DriveLen As Long 

    DriveLen = 255 
    DrivePath = Space(DriveLen) 

    If WNetGetConnection(DriveLetter, DrivePath, DriveLen) = error_success Then 
    GetDrivePath = DrivePath 
    Else 
    GetDrivePath = DriveLetter 
    End If 
End Function 
+0

這個我認爲是在某個地方。現在它提供了缺少的庫錯誤。 – called2voyage

+0

奇怪的是,我找到並確認mpr.dll仍在我的電腦上。 – called2voyage

+0

是否在'PATH'中的文件夾中有'MPR.DLL'? – aphoria

相關問題