本文介绍了从Excel VBA Shell更改工作目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了工作,我正在尝试从Excel VBA宏运行Python脚本.

For work, I'm trying to run a Python script from an Excel VBA macro.

宏如下-

Sub Plot()

Shell "C:\Users\maheshda\AppData\Local\Continuum\Anaconda3\python.exe C:\Users\maheshda\Tool\Tool\Main.py", vbNormalFocus

End Sub

从命令行运行时脚本运行正常,但是不幸的是,因为我在Python脚本中使用了相对文件路径(有一次,我从'../Input/'调用文件),脚本崩溃是因为当前的工作目录不是C:\ Users \ maheshda \ Tool \ Tool.

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!

推荐答案

这是VBA中的一项琐碎任务,请使用 ChDir :

This is a trivial task in VBA, use ChDir:

更改当前目录或文件夹.

Changes the current directory or folder.

语法

ChDir 路径

必需的path参数是一个字符串表达式,用于标识哪个目录或文件夹成为新的默认目录或文件夹.该路径可能包括驱动器.如果未指定驱动器,则ChDir更改当前驱动器上的默认目录或文件夹.

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.

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

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"

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

Or (since it is on drive C):

ChDir "\Users\maheshda\Tool\Tool"

这篇关于从Excel VBA Shell更改工作目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 19:54