Excel VBA Dir() default path? - excel

I am working through an exercise that uses Dir() to find out whether a file exists in the current directory (i.e. the same directory as the workbook I'm using). The code given - and apparently working in the video example - is like this:
IsThere = (Dir("SomeFile.xlsx") <> "")
When I run this code, IsThere returns False. I can work around it by using:
IsThere = (Dir(ActiveWorkbook.Path & "\SomeFile.xlsx") <> "")
but I want to know why Dir isn't looking by default in the current directory as expected.
I'm struggling to find any relevant advice on this. Most of the examples I've found of how to use Dir() are with the file path specified so they don't really shed any light on my problem. The closest I've found is this (obsolete) MSDN reference which says that:
To run correctly, the Dir function requires the Read and PathDiscovery flags of FileIOPermission to be granted to the executing code.
Trouble is, I don't really understand the linked advice in there on how to set PathDiscovery to 1.
As for StackOverflow, this is probably the closest to my problem - although this uses a specified path, and I am not referencing a network location. I note that the answer to this question seems to presume that Dir() should work in the way expected i.e. with a simple filename and not a fully specified path.

This has nothing to do with whatever the host application thinks it's directory is. You can always find out what directory Dir will default to by calling the CurDir function:
Debug.Print CurDir$
If you need to change it, call ChDir:
Debug.Print CurDir$
Debug.Print Dir$("*.*")
ChDir "C:\"
Debug.Print CurDir$
Debug.Print Dir$("*.*")
Think of it like sitting at a command prompt and typing dir or cd - it does exactly the same thing. Note that the current directory holds it's state between macro executions, so you can't rely on it being in some default location.
If you need a path relative to an open Workbook, use Workbook.Path if you need a path relative to the default path, use Application.Path. If you need to test for the existence of a file, don't use Dir at all - use the Scripting.FileSystemObject instead. You'll do yourself a huge favor if start thinking of the legacy file functions as deprecated.

Check the Excel Options --> Save --> Default File location to see what your default is. It won't by default use where the file is located.

Related

'Save As' of object '_workbook' failed

I am trying to save a workbook as xlsm, this is the code I use:
ThisWorkbook.SaveAs Filename:="path\workbook_name.xlsm", FileFormat:=xlOpenXMLWorkbookMacroEnabled
I have done some testing, and It does in fact save in both a private folder and a public or shared folder
however when I save it in a shared folder I also get this:
Run-time error '1004' Method 'Save As' of object '_workbook' failed
why do I get error message when it is saved in a public/shared folder, or onedrive?
In your string containing path there is variable "path" i suppose. Then you should write it like this:
Dim path as String: path = "C:\Users\xxx\Desktop"
ThisWorkbook.SaveAs Filename:=path & "\workbook_name.xlsm", FileFormat:=xlOpenXMLWorkbookMacroEnabled
Or you can hardcode full path (but i recommend using variables - first example).
ThisWorkbook.SaveAs Filename:="C:\Users\xxx\Desktop\file.xlsm", FileFormat:=xlOpenXMLWorkbookMacroEnabled
Then when you can save it manually and you have permissions then i have no idea since i normally save files to shared folders and network drives... Maybe your specific path is wrong. It is best to save using servername and folders...
path = "\\servername\folder1\folder2\workbook_name.xlsm"
Because sometimes when you refefer to mapped drive for example X:\folder2 then you must ensure that all users have it mapped in same way (someone uses X someone uses R etc.). And if path is correct then only other way i can think of it is permission issue, but if you can save it manually then i have sadly no idea... :)

How can I set an universal working directory?

I'm setting up a new algorithm and I want to share it on another computer. How can I set paths with only the folder name, for example.
I've tried to use the function os.chdir(path), but I don't achieve to reach my folder when I'm not using a 'root path' like C:/../../folder.
os.chdir(../folder_name)
By doing os.chdir(../folder_name), you are referring to the parent dir of the current directory.
You probably are looking for the os.chdir(./folder_name), with one dot? This is the current directory, where your script stands.
More here: https://learn.microsoft.com/en-us/dotnet/standard/io/file-path-formats
Update: After clarification in the comments, you want to refer to folder_name from one of its subfolder (/folder_name/library). Then it is indeed .. that you should use, but .. only:
os.chdir(..)

custom function in excel using vba that works in any matchine

I have created a custom function via vba in excel. If I use it in my computer, it works ok, but if I change the file to another computer (where this computer also has the created function), it does not work. I must change the path of the created function. Is there any way to not change the path everytime I copy the file into another computer?
='C:\Users\Usuario1\Documents\Complementos\BondsTIRMDuration.xlam'!TIrbonds($A2;F2;'C:\Users\Usuario1\Documents\Complementos\AsBusinessDay.xlam'!asbusinessday('C:\Users\Usuario1\Documents\Complementos\AsBusinessDay.xlam'!PrevBusinessDay(HOY())))*100
Solution 1: You could use a common paths in both computers
(for example: C:\work , C:\Work2)
Solution 2: You could put all files in the same path (C:\work), then you only need the to put the file name
='BondsTIRMDuration.xlam'!TIrbonds($A2;F2;'AsBusinessDay.xlam'!asbusinessday('AsBusinessDay.xlam'!PrevBusinessDay(HOY())))*100
Just save your add-in in the correct path on every computer.
It should be something like:
C:\Users\YOURNAME\AppData\Roaming\Microsoft\AddIns\
See Install and Use Excel Add-ins to determine the correct path.
If your add-in is installed correctly you should be able to run your user defined function without a path.
You can call special folder with application.
MsgBox Application.DefaultFilePath
This example will be: C:\Users\Usuario1\Documents
'Here are a few VBA path functions
MsgBox Application.Path
MsgBox Application.DefaultFilePath
MsgBox Application.TemplatesPath
MsgBox Application.StartupPath
MsgBox Application.UserLibraryPath
MsgBox Application.LibraryPath
You can too create wscrit object to call another paths, for example:
MsgBox CreateObject("Wscript.Shell").SpecialFolders("Desktop")
Example folders for Wscript.shell object:
AllUsersDesktop
AllUsersStartMenu
AllUsersPrograms
AllUsersStartup
Desktop
Favorites
Fonts
MyDocuments
NetHood
PrintHood
Programs
Recent
SendTo
StartMenu
Startup
Templates
And execute a macro like this,(allways have to use same directory):
Sub Macro()
AddIns.Add Filename:=Application.DefaultFilePath & "\Complement.xlam"
AddIns("Complement").Installed = True
End Sub

pyvmomi specific folder name

Struggling with grasping OOP and pyvmomi in general. Have a question about calling a specific folder by name - it seems that the object names can be folder or VM, and calling hasattr is the best way to differentiate the two?
Also, when I want to call the contents of a specific folder, I've been setting a variable with the name of the folder and looping through each object checking for a match, isn't there a better way, like calling specific object and folder name? I can't see to get it work. Here is what I have right now:
vmfolder = datacenter.vmFolder
vmfolderList = vmfolder.childEntity
folder = "FooFolder"
for i in vmfolderList:
try:
folderName = i.name
if folderName == folder:
vmfolder = i
print(f"Working in folder: {folderName}")
except:
pass
What I have right now doesn't feel very pythonic. I used to write code years ago but it was entirely procedureal and the whole object/attribute thing is a struggle - if anyone recommends a good tutorial or resource as well, it would be appreciated. I feel that once I get over that hurdle I should be able to pick up any SDK and run with it.
Instead of testing using hasattr I would expect folder and VM objects to be of a different type. Checking for a type is entirely pythonic.

VBA - How to get the last modified file or folder in a directory in Excel 2010

What I want to do is more complex than selecting a file from a list of files. I will start in a directory, then I want to change to the most recently modified directory. I then want to repeat that process in a sub-directory, and then, inside of that, I want to select the most recently modified excel file and open it.
What is the best approach to do this?
What objects / methods should I be looking into?
The simplest function is
FileDateTime(pathname)
where pathname can be a directory for folder.
Alternatively, you can use the FileSystemObject object, DateLastModified property:
Dim fileModDate As String
Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.GetFile(<filenamestringhere>)
fileModDate = f.DateLastModified
All of the above can be explored in VBA help.

Resources