【发布时间】:2021-04-23 21:13:51
【问题描述】:
我在 excel 中从 vba 调用 python 脚本时遇到问题,当我运行宏时没有任何反应!
我不知道问题出在哪里?
我在 vba 中的代码:
Option Explicit
Sub Run_python_script()
' declare the variables
Dim objShell As Object
Dim PythonExe, PythonScript As String ' the path of the python file and python script
' create a new shell object
Set objShell = VBA.CreateObject("Wscript.Shell")
'provide the file path to the python exe
PythonExe = """C:\Users\bbbbbb\AppData\Local\Microsoft\WindowsApps\python.exe"""
'provide the file path to the python script
PythonScript = """C:\Users\bbbbbb\OneDrive\Bureau\test_python\test.py"""
'run the python script
objShell.Run PythonExe & PythonScript
End Sub
我正在使用 python 3.7 和 jupyter ide
这是我的python代码:
import pandas as pd
import xlrd
file = r'C:\Users\bbbbbb\OneDrive\Bureau\test_python\test.xlsm'
sheetname='Feuil1'
n=2
df = pd.read_excel(file,skiprows=[*range(n)],index_col=[0])
df_static= df[['CF','VPC','CO','MA','status','Project Naming','Poste','family','ressource']]
wb = xlrd.open_workbook(file)
ws = wb.sheet_by_name(sheetname)
year = ws.cell(0,0).value
month = ws.cell(1,0).value
datetime_cols= pd.to_datetime(df.columns,dayfirst=True,errors='coerce')
out = (df.loc[:,(datetime_cols.year == year) & (datetime_cols.month == month)])
df_merge=pd.concat([df_static,out], axis=1)
df_merge
book = load_workbook(r'C:\Users\bbbbbb\OneDrive\Bureau\test_python\test.xlsm')
writer = pd.ExcelWriter(r'C:\Users\OneDrive\Bureau\test_python\test.xlsm', engine='openpyxl')
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
df_merge.to_excel(writer, "ETP",startcol=0,startrow=6)
writer.save()
我的 Excel 表格“Feuil1”看起来像这样:
当我在单元格 A1 和 A2 中选择年份和月份时,它将使用所选数据生成另一个名为“ETP”的工作表。
所以通过导入pyrhon脚本,每次我选择不同的日期,它都会自动更新
提前感谢您的帮助
【问题讨论】:
-
你的脚本运行了吗?你有什么方法可以知道它是否已经运行?脚本做什么/应该做什么?
-
是的,它已运行,但 Excel 工作簿中没有任何变化!
-
您的脚本是否对当前目录做出假设?通过 Shell 调用与双击调用时,事情可能会有所不同
-
我在我的问题中添加了一些信息以进一步澄清问题
-
您是否尝试更新您运行宏的 same
.xlsm工作簿?您的 Python 脚本可能会在权限问题上出错。抛开 Excel 不谈,Python 脚本是否能够自行成功运行(即终端中的命令行调用)。
标签: python-3.x excel vba