I have an Excel file with a button that calls a Shell command in VB:
Shell(ThisWorkbook.Path & "\python_script.bat", vbNormalFocus)
The Shell command calls the above batch file that runs a Python script:
All the pertinent files (the Excel file, the batch file, the data files, the Python file) are all located in the same directory, call this
sample_program, because I am building this for someone else and I intend for them to simply unzip it and run it.
In Excel, when testing this, I click the button and then get this error:
C:\Users\<user_name>\Documents>python python_script.py python: can't open file 'python_script.py': [Errno 2] No such file or directory
For some reason, although all these files are in the same location, the cmd.exe is running from my user directory:
I don’t want cmd.exe to use this path; I want it to use the
How do I get this to use relative paths so when I transfer this folder to someone else, and they place it anywhere, it will work as a self-contained unit?
Try this, if
path\to\sample_program is on the same drive as your home drive
Shell "cmd.exe /k cd " & ThisWorkbook.Path & "&&python_script.bat"
or this if
path\to\sample_program is not on the same drive as your home drive, or you dont know in advance
Shell "cmd.exe /k " & Left(ThisWorkbook.Path, 2) & "&&cd " & ThisWorkbook.Path & "&&python_script.bat"
You can use
Environ("username") to get the user logon name, so for your sample (which I presume is Windows 7)
Sub GetDir() MsgBox "C:\Users\" & Environ("username") & "\Documents" End Sub
You can also automatically retrieve certain locations regardless of OS using SpecialFOlders, ie
Sub GetPath() Set wshShell = CreateObject("WScript.Shell") Documents = wshShell.SpecialFolders("MyDocuments") MsgBox Documents End Sub