简体   繁体   English

从Excel运行批处理文件时,确保在cmd.exe中使用了相对路径

[英]Ensure Relative Path is Used in cmd.exe when Running Batch Files From Excel

I have an Excel file with a button that calls a Shell command in VB: 我有一个带有按钮的Excel文件,该按钮在VB中调用Shell命令:

Shell(ThisWorkbook.Path & "\python_script.bat", vbNormalFocus)

The Shell command calls the above batch file that runs a Python script: Shell命令调用上面运行Python脚本的批处理文件:

python python_script.py

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. 所有相关文件(Excel文件,批处理文件,数据文件,Python文件)都位于同一目录中,将此文件称为sample_program ,因为我正在为其他人构建此文件,并且打算让他们简单地将其解压缩并运行它。

In Excel, when testing this, I click the button and then get this error: 在Excel中,当对此进行测试时,我单击按钮,然后出现此错误:

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: C:\\Users\\<user_name>\\Documents 由于某些原因,尽管所有这些文件都位于同一位置,但cmd.exe从我的用户目录运行: C:\\Users\\<user_name>\\Documents

I don't want cmd.exe to use this path; 我不希望cmd.exe使用此路径; I want it to use the path\\to\\sample_program directory. 我希望它使用path\\to\\sample_program目录。

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 如果path\\to\\sample_program与主驱动器在同一驱动器上,请尝试此操作

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 否则,如果path\\to\\sample_program与您的主驱动器不在同一驱动器上,或者您事先不知道

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) 您可以使用Environ("username")来获取用户登录名,因此对于您的示例(我假设是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 您也可以使用SpecialFOlders自动检索某些位置,而不管操作系统如何,即

Sub GetPath()
Set wshShell = CreateObject("WScript.Shell")
Documents = wshShell.SpecialFolders("MyDocuments")
MsgBox Documents
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM