Map Network Drive in Visual Basic 2010 - vb.net

I have spend months now trying to get the Visual Basic 2010 codes on how to map a network drive, disconnect them, and re-map network driver.
I will need to be able to map it to the profile folder to something like this:
Full path; “\10.10.10.12\Profile folder".
I need to log in to have access to the network folder /user:Domainname\UserName Password,
then confirm if mapping was successful with a message.
After the mapping I will request the profile name and check if such profile folder exists on the network.
If it exists, return a message stating that the profile exists, and delete the profile folder overwriting any folder property like if reading only, etc.
There are other tasks but his is where I am hit a dead end.

This question is old but maybe the OP is still looking. I wrote an HTA page awhile back to map a network address to a virtual drive. The code is VBScript and so uses the WScript library, which is not a native part of VB.net. See WScript in VB.Net on StackOverflow for more info on that.
The connect script:
SUB doLogOn()
Dim objNetwork, errNum, ojbFSO, strDrive, iNum
Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.FolderExists("\\MyServer\MyFolder\") = False Then
strDrive = "J:"
Set objNetwork = CreateObject("WScript.Network")
On Error Resume Next
objNetwork.MapNetworkDrive strDrive, "\\MyServer\MyFolder", False, "username", "password"
If Err.Number <> 0 Then
Err.Clear
End If
Set objFSO = Nothing
Set objNetwork = Nothing
End If
END SUB
Personally, I haven't found code to do the same thing in .Net. The VBScript shown above is pretty primitive; I hope it plus the info on binding WScript gives you an idea or two, though.
Edit: see Eric Dalnas' code, here

Related

Excel VBA to open Sharepoint folder and create list of hyperlinks for files within

Prior to being asked to migrate to SharePoint, I was using a collection of .xlsm files to set project teams up to manage projects. My Project Manager file included a macro that would go to a designated folder and create hyperlinks for all current project files. I've saved the collection of .xlsm files on SharePoint, but when I run the macro below (which I found here - Thank you!), I receive an error related to the "Set xFolder = xFSO.GetFolder(xPath)" line. Any help would be great. I've read several posting that may have the answer and tried several adjustments to the code, with no luck.
Sub Create_Hyperlinks_for_all_Current_Projects()
Range("B8:D38").Clear
MsgBox "Once you click OK, an explorer box will appear. Select the folder
containing all the CSTPs and then click OK again. HINT: The folder
containing all the CSTPs should be in the same folder this document was in
and should be called ''CSTPs''. Links to all CSTPs will then appear in the
white box on the Manager Menu."
Dim xFSO As Object
Dim xFolder As Object
Dim xFile As Object
Dim xFiDialog As FileDialog
Dim xPath As String
Dim I As Integer
Set xFiDialog = Application.FileDialog(msoFileDialogFolderPicker)
With xFiDialog
.InitialFileName = ThisWorkbook.Path
End With
If xFiDialog.Show = -1 Then
xPath = xFiDialog.SelectedItems(1)
End If
Set xFiDialog = Nothing
If xPath = "" Then Exit Sub
Set xFSO = CreateObject("Scripting.FileSystemObject")
Set xFolder = xFSO.GetFolder(xPath)
For Each xFile In xFolder.Files
I = I + 2
ActiveSheet.Hyperlinks.Add Cells(I + 6, 2), xFile.Path, , , xFile.Name
Next
End Sub
I hope you find the following notes helpful.
They summarize the outcomes from several weeks of frustration.
If you are using SP365,
then the filesystemobject
no longer works very well, if at all.
I had hundreds of macros dependent on the FSO.
These have all worked great up until my organization migrated to SP365 :o(
Now they only work if I manually click
the Open Explorer button, in SP, first.
Opening Explorer provides Win Explorer with the required permissions to access SP.
This in turn provides the FSO with the required permissions to access SP.
But...in my case...FSO only works for a while.
For my first work around...
I rolled out a prototype app, which used a macro to automate
opening IE, opening Win Explorer and initializing permissions for the FSO
All worked great on my machine, for about an hour,
then some kind of timeout took me back to square one.
Colleagues on other machines experienced a range of FSO behaviours.
From all working ok. To having to rerun the connection macro every 30 seconds.
To nothing working at all.
I then invested time trying to update macros to connect to SP as a network drive.
Again, this is a process that I have used for years, up until migration to SP365.
Again, success connecting to SP365 seems to be very machine dependent.
In the end...with respect to my own requirements...
My work around was to create an SP view that lists all files.
Then use the Export to Excel option in SP to create an Excel data query.
Then copy the query into an Excel file that I refer to as Config.xlsx.
Then use Excel RefreshAll to update the list of files, each time a list is required.
Its not very elegant...but, it works ;o)
As I say....I hope this helps you / someone.
Feel free to connect on LinkedIn if you require any followup advice.
Peter,
LinkedIn name DrPeterEHSmee

"Disconnected Network Drive" in My Computer

We use VPN to connect to the work network. I have a mapped network drive that shows "Disconnected Network Drive" in My Computer immediately after I connect. While in this state I run a VBA routine:
Dim dr As String: dr = "F:\T\"
Dim fso: Set fso = CreateObject("Scripting.FileSystemObject")
If Not fso.FolderExists(dr) Then
Call fso.CreateFolder(dr)
End If
Even though the folder actually does exist, fso thinks it doesn't so it tries to create the folder and throws an error: Run-time error 76: Path not found. Of course it can't find it because it is in a disconnected state. Any other operations using that network drive will fail too.
So I open My Computer and manually double-click the network drive. It connects just fine and I no longer get the error when running the code again. But this is problematic. I need a solution in the code to automatically connect the network drive.
Possible solution 1: Just use the UNC path instead of mapped drive letter. The problem with that is that I don't know what the path is. Nor do I want to use UNC; the code needs to be flexible to work with wherever the drive maps to. It's policy from the brass.
Possible solution 2: Re-map the network drive using Net Use or WshNetwork. Again, this isn't really possible as I don't know what the UNC path is or will be.
Possible solution 3: Connect using ShellExecute While this would work, it isn't really palatable as it opens a window to explore the folder (could use SW_HIDE to avoid showing the window, but then how would I close it?). Furthermore it doesn't connect instantly. I would need a delay of uncertain length to make this work. Not a good answer. MSDN ShellExecute Function
So is there a better solution? How do I connect the drive while waiting for it to return and throwing an error if not able to connect?
I need it to work for both VBScript and VBA.
Slugster's suggestion to get the mapped UNC value is a good one. Here is my solution as adapted from this answer This works for VBScript and VBA.
Sub testget()
Debug.Print getUNC("F:\T\")
End Sub
Function getUNC(dir)
Dim fso: Set fso = CreateObject("Scripting.FileSystemObject")
Dim sDrive: sDrive = fso.GetDriveName(dir)
Set fso = Nothing
Dim sMap: sMap = GetMappedDrive(sDrive)
If sMap <> "" And sDrive <> sMap Then
getUNC = Replace(dir, sDrive, sMap)
Else
getUNC = dir
End If
End Function
Function GetMappedDrive(sDrive)
Dim wshNetwork: Set wshNetwork = CreateObject("WScript.Network")
Dim oDrives: Set oDrives = wshNetwork.EnumNetworkDrives
Dim i
For i = 0 To oDrives.Count - 1 Step 2
If UCase(oDrives.Item(i)) = UCase(sDrive) Then
GetMappedDrive = oDrives.Item(i + 1)
Exit For
End If
Next
Set oDrives = Nothing
Set wshNetwork = Nothing
End Function

Toggle Windows Explorer "Work Online" mode via Excel VBA

I have written several VBA macros that access intranet network locations. They work well when users are located on-site. However, when they are off-site and accessing the network via VPN, these network locations are not available unless they manually navigate to them via Windows Explorer and select the "work online" option at the top of the explorer window.
I can already verify whether they are connected via VPN programmatically.
What I need is to be able to perform the equivalent of activating "work online" mode via Excel VBA.
Any suggestions from the hive mind?
Didn't have any success via Google or existing SO posts.
Simplest approach would be to trap the error when the folder cannot be accessed, display a message box to inform the user of the required option, and use Shell command to open the Windows Explorer:
Dim Foldername As String
Foldername = "\\UNCPATH\TO\NETWORK_DRIVE\"
Shell "C:\WINDOWS\explorer.exe """ & Foldername & "", vbNormalFocus
Alternatively, you may be able to get this to work, although I could not, it was too long to post as a comment so I will include the procedure here:
Sub fnOfflineStatusVB()
Dim objShell As Object 'IShellDispatch5
Dim objFolder As Object 'Folder3
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace("\\UNCPATH\TO\NETWORK_DRIVE\")
If (Not objFolder Is Nothing) Then
Dim nReturn As Integer
nReturn = objFolder.OfflineStatus()
End If
Set objFolder = Nothing
Set objShell = Nothing
End Sub
Found it here
Found PowerShell commands that can be executed through CMD successfully. Roadblock that remains is integrating these into a batch file.
These CMD commands work when entered manually:
powershell.exe -noexit "$oWMI=[wmiclass]""\\localhost\root\cimv2:win32_offlinefilescache"""
$oWMI.TransitionOnline("<path here>")
Where "Path here" in angle brackets is an UNC path on my network. However, executing them in a batch file has been unsuccessful thus far.
Here is the code:
#ECHO ON
::Move to non UNC Path directory
cd /D "C:\"
powershell -NoExit -Command "& {'$oWMI=[wmiclass]''\\localhost\root\cimv2:win32_offlinefilescache';$oWMI.TransitionOnline('<Path here>')}"
:: Pause CMD window to give user confirmation that execution has occurred
PAUSE
If anyone has any suggestions on the issue, your advice would be greatly appreciated.
Running PowerShell scripts directly are not permitted due to Group Policy set by IT, which is the reason for this round-about method.

lotus notes to VBA

I'm stuck with this problem for days
I have to read a specific mailbox in lotus notes and bring all the content into an excel spread sheet
but so far I have only been able to read the default inbox and have no way of switching to the other mailbox. I 'm really new to VBA can any one help me sort this out
here is the code I 'm using
Set NSession = CreateObject("Notes.NotesSession")
'get the name of the mailfile of the current user
DbLocation = NSession.GETENVIRONMENTSTRING("mail/mailbox", True)
'Get the notesdatabase for the mail.
Set NMailDb = NSession.GETDATABASE("mailboxer", DbLocation)
MsgBox (DbLocation)
I get an empty msgbox poping up
GetEnvironmentString() reads the notes.ini file. I'm not sure that's what you really want to be doing. Just from the syntax, I think you're using "mail/mailbox" as a placeholder for the actual path to the mailbox that you're looking for. E.g., you're really trying to read the mail from something like "mail/jsmith.nsf". (If I'm wrong, and you really do want to be reading the notes.ini file to get the location of the mail file, then your problem is that "mail/mailbox" is not a valid key for an ini file entry.)
My next assumption is that the Domino server where the mailbox lives is called "mailboxer", because that's what you're putting in the first argument of GetDatabase().
If I'm right about these things, then what what you need is
Set NMailDb = NSession.GETDATABASE("mailboxer", "mail/mailbox")
where "mail/mailbox" is replaced with the actual path to the mailbox that you are trying to open.
Some thoughts:
use Lotus.NotesSession if you don't have to interact with the Notes UI (Lotus.NotesSession is COM based, whereas Notes.NotesSession is OLE based)
make sure the user of the Notes client on the workstation running your VBA application has the rights require to open and read the mailbox
As D. Bugger stated, you need to be sure you have the Notes client installed on the same client machine your VB code will run, and you need to be sure the folder with the nnotes.exe file and the folder with the notes.ini file are in your environment path. (If not, you will get a COM error instantiating the Notes.NotesSession object.
If this helps, here is some starter code - not tested, but a rough guide... This walks through all documents in a Notes mailbox database, ignores anything except email documents (which have the form field = "Memo") and grabs some fields from each email.
Public Sub exportNotesMail(MailServer$, MailDBPath$)
Dim mailDb As Object, doc As Object, alldocs As Object, Session As Object
Set Session = CreateObject("Notes.NotesSession")
Set mailDb = Session.GETDATABASE(MailServer, MailDbPath$)
If mailDb.IsOpen = False Then mailDb.OPENMAIL
Set alldocs = mailDb.AllDocuments
Set doc = alldocs.GetFirstDocument
while not (doc is nothing)
If doc.GetItemValue("Form")(0) = "Memo" Then
thisSubject = doc.getItemValue("Subject")(0)
thisFrom = doc.getItemValue("From")(0)
' get more field values
' Export to Excel or wherever
End If
Set doc = alldocs.GetNextDocument(doc)
Next i
' done
End Sub
call exportNotesMail ("MyServer", "mail\myMailFile.nsf")

Permission Denied Error During Update of a Local MSOffice Add-In from Network

I am attempting to write a procedure in PowerPoint 2003 that will allow automatic updating of an installed add-in. The general process is as follows:
Uninstall the add-in
For Each objAddIn In Application.AddIns
If UCase(objAddIn.Name) = UCase(AddInName) Then
With objAddIn
.Registered = msoFalse
.AutoLoad = msoFalse
.Loaded = msoFalse
End With
End If
Next
Delete the file from the local Add-Ins directory
Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.FileExists(FileName) Then
Set objFSO = Nothing
Kill FileName
End If
Copy over the file from the network location
Install the updated add-In
Upon reaching step 2, any attempt at deleting the file post-uninstall using either the FileSystemObject or a straight Kill inevitably generates Run-time error '70': Permission denied. If I hit Debug and then play, it runs through as if there was never a problem.
Side note: I realize I can use FSO to overwrite the local file, but that gives me the same run-time error.
I'm guessing the problem has to do with some aspect of the file being in use, but I can't figure out how to "release" the old add-in so that the underlying file can be deleted.
Does anyone have insight that can help?
You need to remove it from the Addins Collection before it can get physically deleted. Put this, right after your End With:
Application.AddIns.Remove objAddIn.Name
The KB Article that refers to a VBA function you can use to CHECK for a locked file is here.
http://support.microsoft.com/kb/209189
It contains a simple function you can add to your VBA to check that a file is not locked and uses the same code sample that Otaku refers to in his answer.
What I would do is...
Replace the Kill Filename line in your code
If FileLocked(Filename) = True Then
SetAttr Filename, vbNormal
Kill Filename
End If
*Where FileLocked is a custom function referred to in KB209189
**If this doesn't work, reply back, we could also look at replacing the Kill statement above with a lower level Win32 function that does the same thing (but perhaps more throughly). :D