从Excel vba shell更改工作目录

对于工作,我试图从Excel VBAmacros运行Python脚本。

macros观如下 –

Sub Plot() Shell "C:\Users\maheshda\AppData\Local\Continuum\Anaconda3\python.exe C:\Users\maheshda\Tool\Tool\Main.py", vbNormalFocus End Sub 

从命令行运行脚本运行得很好,但是不幸的是,因为我在Python脚本中使用了相对的文件path(在某个时刻,我调用了“../Input/”中的文件),脚本崩溃了,因为当前的工作目录不是C:\ Users \ maheshda \ Tool \ Tool。

我如何从macros内改变工作目录? 谢谢!

这在VBA中是一个简单的任务,使用ChDir

ChDir声明

更改当前目录或文件夹。

句法

ChDir path

所需的path参数是一个stringexpression式,用于标识哪个目录或文件夹成为新的默认目录或文件夹。 path可能包括驱动器。 如果未指定驱动器,则ChDir更改当前驱动器上的默认目录或文件夹。

由于您的main.py驻留在C:\Users\maheshda\Tool\Tool\ ,请调用Python脚本之前使用以下内容:

 ChDir "C:\Users\maheshda\Tool\Tool" 

或者(因为它在驱动器C上):

 ChDir "\Users\maheshda\Tool\Tool" 

扩展WiktorStribiżew的回答和评论,下面的子可以在任何情况下用于更改当前目录。

 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 

快乐的编码!

FCastro,你为什么打扰StrComp线? 而且,为什么要打扰string对象?

我想如果驱动器是外部的,并且还没有被访问,则可能需要一些时间,但是只要path不是USB / CD / DVD /等等,则:

 Public Sub Change_Current_Directory(NewDirectoryPath as string) ChDrive Left(NewDirectoryPath,1) ChDir NewDirectoryPath End Function