Get the current directory from VBA - vba

in VBA there is a ChDir function that allows to set/change the current directory.
That Current Directory is also affected by a user browsing through his drives/folders from Access (or Excel), even if he clicks Cancel in the end without opening anything.
My question is: in the later case, how do I retrieve the Current Directory ?
Note: the CurrentDirectory has nothing to do with the folder of the CurrentDb!

You want CurDir$:
?CurDir$
c:\temp
ChDir "c:\windows\"
?CurDir$
c:\windows

The complement to the ChDir command in VBA is the CurDir function.

on VBS
Dim WshShell
Set WshShell = WScript.CreateObject("WScript.Shell")
WScript.Echo WshShell.CurrentDirectory

Related

Folder handle not released after Dir checks for existence

The following code checks to see if a folder exists and, if not, creates it. The code works, but a handle that points to the folder is left open if it already exists, which prevents the folder from being deleted or renamed until Outlook.exe closes. I do not understand why this is happening or what to do about it, but a handle should not be open after the folder is checked and potentially created.
Sub Test()
Folder = Environ("USERPROFILE") & "\Desktop\NewFolder\"
Result = Dir(Folder, vbDirectory)
If Result = vbNullString Then
MkDir Folder
End If
End Sub
The first time through the code, the folder is successfully created and no file handles are open:
However, the second time through the code, the folder already exists. MkDir does not execute, but a file handle is left open presumably after Dir executes:
I have tried everything I could find to close all open file handles, but nothing has worked. Any help would be greatly appreciated.
Based on the comments from braX, I was able to prove that the Dir call was somehow responsible for the leftover handle. Calling Dir again on a non-existent folder caused the handle to be released, which solved my problem.
A better solution, which was also suggested by braX, is to use a File System Object. Here is a working solution:
Sub Test()
Dim FSO As FileSystemObject
Set FSO = CreateObject("Scripting.FileSystemObject")
Folder = Environ("USERPROFILE") & "\Desktop\NewFolder\"
If Not FSO.FolderExists(Folder) Then
MkDir Folder
End If
End Sub
Thanks, braX!

Default Filename for GetOpenFilename

I'm looking to set a default filename in GetOpenFilename. I'm using GetOpenFilename because it was in an example for using UNC paths (which I require) and from what I've read you cannot do that with ChDir or ChDrive using FileDialog. Is there anything that exists that will allow presetting of the filename and work with UNC paths?
I've tried sticking the filename into the FileFilter section of GetOpenFilename and that does not work. From what I have found it looks like this may not be possible but my limited knowledge of VBA may be the issue as well.
I'm stuck with using UNC because the data is located on a network and not everyone maps it to the same drive or even maps it at all.
In Excel if you look in Application.Dialogs() you'll find a long list of predefined dialog boxes used in Excel that you can call upon. GetOpenFilename is the same situation, because it is predefined, the customization options are minimal.
To use the generic file dialog box (i.e. not custom within Excel) you can use Application.FileDialog(msoFileDialogOpen), this will allow for further customisation including the initial filename text.
Public Sub Sample()
Dim Dlg As FileDialog
Set Dlg = Application.FileDialog(msoFileDialogOpen)
Dlg.InitialFileName = "Sample"
Dlg.Show
Set Dlg = Nothing
End Sub

Changing working directory from Excel vba shell

For work, I'm trying to run a Python script from an Excel VBA macro.
The macro is as follows -
Sub Plot()
Shell "C:\Users\maheshda\AppData\Local\Continuum\Anaconda3\python.exe C:\Users\maheshda\Tool\Tool\Main.py", vbNormalFocus
End Sub
The script runs just fine when run from the command line, but unfortunately, because I'm using relative filepaths in the Python script (at one point, I call files from '../Input/') the script crashes because the current working directory isn't C:\Users\maheshda\Tool\Tool.
How can I change the working directory from within the macro? Thank you!
This is a trivial task in VBA, use ChDir:
ChDir Statement
Changes the current directory or folder.
Syntax
ChDir path
The required path argument is a string expression that identifies which directory or folder becomes the new default directory or folder. The path may include the drive. If no drive is specified, ChDir changes the default directory or folder on the current drive.
Since your main.py resides in C:\Users\maheshda\Tool\Tool\, use the following right before calling the Python script:
ChDir "C:\Users\maheshda\Tool\Tool"
Or (since it is on drive C):
ChDir "\Users\maheshda\Tool\Tool"
Extending on Wiktor Stribiżew's answer and comments, the sub below can be used to change the Current Directory in any case.
Public Sub Change_Current_Directory(NewDirectoryPath as string)
Dim CurrentDirectoryPath as string
CurrentDirectoryPath = curdir
if Strings.StrComp(Strings.Left(CurrentDirectoryPath,2), Strings.Left(NewDirectoryPath,2), vbTextCompare) then
ChDrive Strings.Left(NewDirectoryPath,1)
end if
ChDir NewDirectoryPath
End Function
Happy coding!
FCastro, why did you bother with that StrComp line? And, for that matter, why bother with the Strings object?
I suppose if the drive were external and hadn't been accessed yet it might take a moment, but as long as the path is not expected to be a USB/CD/DVD/etc..., then:
Public Sub Change_Current_Directory(NewDirectoryPath as string)
ChDrive Left(NewDirectoryPath,1)
ChDir NewDirectoryPath
End Function
If your behavior is to open an excel window and then open your recent file, please note that you should not forget to add change Drive and then change Directory into your VBA code.
Cause the Excel always start with the default Directory even it's just open your recent file !
Dim ThisWorkbookPath As String
Dim ThisWorkbookPathParts As Variant
ThisWorkbookPath = ThisWorkbook.Path
ThisWorkbookPathParts = Split(ThisWorkbookPath, _
Application.PathSeparator)
ChDrive ThisWorkbookPathParts(LBound(ThisWorkbookPathParts))
ChDir ThisWorkbookPath

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.

VB.NET | Get current user profile folder

How can I use 'path' to go to the user's current profile?
For example, I have this code:
Dim fso, fldr
fso = CreateObject("Scripting.FilesystemObject")
fldr = fso.GetFolder("C:\Documents and Settings\%UserProfile%\Local Settings\TEST")
'delete subfolders
For Each subf In fldr.SubFolders
subf.Delete(True)
Next
'delete subfiles
For Each fsofile In fldr.Files
fsofile.Delete(True)
Next
I've tried this way and the path is unknown.
How can I make C:\Documents and Settings\???\Local Settings\TEST
to go to the current user's folder?
Use the 'userprofile' environment variable...
MsgBox(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile))
On my Windows 8.1, I cannot access Local Settings folder. It's right protected. As far as getting the right folder path is concerned, I think the answer is already posted above. Just append your custom folder path to the UserProfile Folder path returned by Environment of DotNet.
Something like:
Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) & "\Local Settings\TEST"
Get the Local AppData folder:
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)
And then concatenate it with your "TEST" folder using Path.Combine method.
See SpecialFolders and Combine msdn pages.
This worked for me, using VB6.0 Sp6
Dim myDocuPath As String
myDocuPath = Environ$("USERPROFILE") & "\My Documents"