简体   繁体   English

无法从 Excel (xlwings) 运行 Python

[英]Can't run Python from Excel (xlwings)

I'm quite new to xlwings and I'm runing code from VBA in order to excecute a python script that writes some text in Excel.我对 xlwings 很陌生,我正在运行 VBA 中的代码,以便执行在 Excel 中写入一些文本的 python 脚本。

The problem is when I run the VBA code, it seems to excecute python but my excel sheet doesn't change.问题是当我运行 VBA 代码时,它似乎执行 python 但我的 excel 表没有改变。 However, if I run the python script from python, it works just fine, even if the Excel file is already open.但是,如果我从 python 运行 python 脚本,它工作得很好,即使 Excel 文件已经打开。

VBA code is the following: VBA 代码如下:

Sub Botón1()
Dim obj As Object
Dim pyexe, pyscript As String

Set obj = VBA.CreateObject("Wscript.Shell")
pyexe = """C:\Users\xxx\AppData\Local\Programs\Python\Python36-32\python.exe"""
pyscript = "C:\Users\xxx\Documents\Prueba.py"

obj.Run pyexe & pyscript, 1, True
End Sub

And python code is the following: python 代码如下:

import xlwings as xw

wb = xw.Book('Libro1.xlsm')
sht = wb.sheets['Hoja1']
sht.range('A1').value = 'Hi!'

Both files (Libro1.xlsm and Prueba.py) are saved inside the same folder.两个文件(Libro1.xlsm 和 Prueba.py)都保存在同一个文件夹中。 When I run excel macro it opens the cmd prompt but nothing happens in Excel spreasheet.当我运行 excel 宏时,它会打开 cmd 提示,但在 Excel 电子表格中没有任何反应。 I have not installed xlwings add in, but I believe it is not necessary to do it, in order to do what I'm trying to do.我还没有安装 xlwings add in,但我相信没有必要这样做,为了做我想做的事。

Can you please help me find what could be wrong?你能帮我找出可能是什么问题吗?

I was reading this article: https://devblogs.microsoft.com/scripting/how-can-i-get-the-command-window-to-stay-open-after-running-a-command-line-tool/我正在阅读这篇文章: https://devblogs.microsoft.com/scripting/how-can-i-get-the-command-window-to-stay-open-after-running-a-command-line-tool/

And it explains using.run is equivalent to calling Cmd.exe.它解释了using.run相当于调用Cmd.exe。 If I open cmd I just need to write my python file name with.py extension to run it.如果我打开 cmd 我只需要写我的 python 文件名和.py 扩展名来运行它。 So I figured out "pyexe" is not necessary.所以我发现“pyexe”是没有必要的。

The solution:解决方案:

Sub Botón1_Haga_clic_en()
Dim obj As Object

Set obj = CreateObject("Wscript.Shell")
obj.Run "C:\Users\xxx\Documents\Prueba.py", 1, True

End Sub

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

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