我有一个工作簿,当用户首次登录时,无法打开共享驱动器中的链接,因为共享驱动器显示为“已断开连接”,直到您转到文件资源管理器并手动打开它为止。
之后链接就可以工作了。
我只是希望能够在 VBA 中执行此操作,以防止在驱动器处于断开连接状态时出现找不到文件的情况。
我已经在使用完整的 UNC 文件路径,而不是驱动器号。
有没有简单的代码可以重新连接文件路径?
我已经滚动浏览帖子试图找到答案,但找不到我需要的东西。
提前致谢。
这里是快速准备的代码,用于连接网络共享驱动器并执行一些操作,然后再次断开连接。根据您的需要尝试一下。
Public Sub TestNetShareName()
Dim NetworkObject As Object
Dim FSO As Object
Dim Directory As Object
Dim Filename As Object
Dim ServerShare As String
Dim UserName As String
Dim Password As String
Dim i As Long
ServerShare = "\\192.168.0.10\Tag"
UserName = "UserName"
Password = "YourPassword"
Set NetworkObject = CreateObject("WScript.Network")
Set FSO = CreateObject("Scripting.FileSystemObject")
NetworkObject.MapNetworkDrive "", ServerShare, False, UserName, Password
' NetworkObject.MapNetworkDrive "X:", ServerShare, False, UserName, Password
' Use above line to map a network drive with Drive Letter
Set Directory = FSO.GetFolder(ServerShare)
i = 1
For Each Filename In Directory.Files
Range("A" & i) = Filename.Name
i = i + 1
Next
Set Filename = Nothing
Set Directory = Nothing
Set FSO = Nothing
NetworkObject.RemoveNetworkDrive ServerShare, True, False
' NetworkObject.RemoveNetworkDrive "X:", True, False
' Use above line to disconnect a mapped network drive
Set NetworkObject = Nothing
End Sub