2014-03-05 144 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

相关问题