Access to a shared network folder

I need to get through VBA a folder hosted on a network file server. The folder is available in writing only through a service account (other than regular user accounts), for which I have a username and password.

Through the user interface, I can see this folder and display it as a local drive, but to access it in writing, I need to exit Windows and log in through the service account.

Is there a way to access the network folder during a regular user session, but the username is hardcoding and pwd in VBA code?

I tried to map the folder as a local drive using:

Set WshNetwork = CreateObject("WScript.Network") WshNetwork.MapNetworkDrive "S:", "\\corp-server\HostingFolder", False, Username, pwd 

but does not work (drive "S" was not displayed). If instead I do the same, but without specifying a username and password:

 Set WshNetwork = CreateObject("WScript.Network") WshNetwork.MapNetworkDrive "S:", "\\corp-server\HostingFolder" 

It works great.

I wonder if what I'm trying to do can actually be possible? If not, is there an alternative?

thanks

+6
source share
1 answer

You can find this answer in your testing.

Essentially, I would check a couple of things ...

  • Make sure you are not connected to this resource using the current user. If so, you may receive an error message that resembles the following: enter image description here

  • Make sure you use the domain\username syntax in your username.

Otherwise, I think you are the right way. I collected some code examples based on the link above and was able to successfully connect to the network resource under a different username and iterate over the list of files.

(Pay attention to the hint, which in fact you do not need to map the drive to establish a connection.)

The following code is a really fast (working) implementation of the VBA sample specified in Accessing a network resource from VBScript, for example, FileSystemObject

 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 ServerShare = "\\corp-server\HostingFolder" UserName = "mydomain\myuser" Password = "freddie123" Set NetworkObject = CreateObject("WScript.Network") Set FSO = CreateObject("Scripting.FileSystemObject") NetworkObject.MapNetworkDrive "", ServerShare, False, UserName, Password Set Directory = FSO.GetFolder(ServerShare) For Each Filename In Directory.Files Debug.Print Filename.Name Next Set Filename = Nothing Set Directory = Nothing Set FSO = Nothing NetworkObject.RemoveNetworkDrive ServerShare, True, False Set NetworkObject = Nothing End Sub 
+5
source

Source: https://habr.com/ru/post/978990/


All Articles