通过VBA运行Python脚本并给出活动工作簿的名称和路径?

2024-09-30 01:32:27 发布

您现在位置:Python中文网/ 问答频道 /正文

编辑:这是同一个问题,但我重写了它,所以它更清晰。在

我已经试过这个帖子:How to call python script on excel vba?

还有这个帖子:Run and execute a python script from VBA

还有这个帖子:How can I call python program from VBA?

但这些答案都不适合我,我也不知道我做错了什么。问题1:我想从VBA excel运行pythonscript。excel文件没有主位置(可以在任何桌面上)。我(想)使用的代码:

 Dim Ret_Val
 Ret_Val = Shell("C:\python27\python.exe \\10.31.13.22\SharedDocs\3 - Technical\13 - Reports & Templates\13 - Description\DescriptionToDatabase.py")

pythonfile在服务器上的路径始终相同。我看不出这里有什么不对?我得到的只是一个黑色的python屏幕。在

在python文件中,我调用工作簿和正确的工作表:

^{pr2}$

目前excel工作簿路径是用python硬编码的。这将使我回到问题2:我可以将excel工作簿的名称和路径以某种方式传递给pythonscript吗?在

编辑:

我在命令提示符下尝试了shell()代码。 与VBA相同:

"C:\python27\python.exe \\10.31.13.22\SharedDocs\3 - Technical\13 - Reports & Templates\13 - Description\DescriptionToDatabase.py"

这不管用。”系统找不到指定的路径“”。在

我试过这个:

C:\python27\python.exe "\\10.31.13.22\SharedDocs\3 - Technical\13 - Reports & Templates\13 - Description\DescriptionToDatabase.py"

而且很管用!因此cmd需要“”来处理路径中的空格。但我不能在VBA中添加它们,因为我不能放置2“,否则会出错。在


Tags: py路径编辑descriptioncallvbaexcelexe
2条回答

I was wondering if it is possible to give the name and the path of the active excel workbook to a python script I call from this active workbook?

是的。You can pass argument(s) to ^{} function from VBA,然后您需要修改python脚本以接受参数并对其/它们执行某些操作。在

Python Read from Stdin with Arguments

Python read from command line arguments or stdin

是的,我找到了问题1的解决方案:

Dim excelToPython As String
excelToPython = """C:\python27\python.exe"" ""\\10.31.13.22\SharedDocs\3 - Technical\13 - Reports & Templates\13 - Description\DescriptionToDatabase.py"""
Debug.Print excelToPython
Call Shell(excelToPython)

感谢“艾伦·布朗”(https://bytes.com/topic/access/answers/520558-problem-shell-space-file-name

编辑:

最后,我找到了解决问题2的方法。我仍然没有真正的解决方案,用shell命令为python脚本提供活动工作簿的名称和路径。在

但是我将活动工作簿的路径和名称写在一个txt文件中,与python脚本位于同一个文件夹中。然后我用我的Python文字得到了这个信息。。它起作用了!好吧,这是我想要的,但这不是一个干净的解决方案。如果有人知道正确的解决方案,请随时分享:o)

我的解决方案:

vba excel中的代码:

^{pr2}$

python代码:

filepath ='//10.31.13.22/SharedDocs/3 - Technical/13 - Reports & Templates/13 - Description/actWBdb.txt'
lines =  open(filepath).read().splitlines()
nameWorkbook = lines[0]
pathWorkbook = lines[1]

book = xlrd.open_workbook(pathWorkbook + '/' + nameWorkbook)
sheet = book.sheet_by_name("Database")

相关问题 更多 >

    热门问题