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!
Extending on Wiktor Stribiżew's answer and comments, the sub below can be used to change the Current Directory in any case.
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:
This is a trivial task in VBA, use
ChDir
:Since your
main.py
resides inC:\Users\maheshda\Tool\Tool\
, use the following right before calling the Python script:Or (since it is on drive C):
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 !