【问题标题】:Problem with calling python script from in excel vba从excel vba中调用python脚本的问题
【发布时间】: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


【解决方案1】:

你需要在你的 shell 执行字符串中添加一些空格, 请参阅我的示例代码。

Option Explicit

Sub Run_python_script()
' declare the variables
Dim PythonExe, PythonScript As String ' the path of the python file and python script
    '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
    Shell PythonExe & " " & PythonScript, vbNormalFocus
End Sub

我修复了你的代码,测试了它,它在这里工作。 但是有一个问题,在 excel 中,当文件在 excel 程序中打开时,您不会写入“xlsm”文件。因此,您将无法直接从同一个电子表格运行。 我建议你修改你的python代码,通过命令行传递参数,比如文件名和目录。

先在终端上测试这段代码

你的python代码:

import pandas as pd
import xlrd 
from openpyxl.reader.excel import load_workbook
from openpyxl import Workbook
file = r'C:\dev\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 = load_workbook(file, read_only=False, keep_vba=True)
ws = wb.worksheets[0]
year = ws['A1'].value
month = ws['A2'].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 = wb
writer = pd.ExcelWriter(r'C:\dev\Test.xlsm', engine='openpyxl') 
writer.book = book
writer.vba_archive = book.vba_archive


writer.sheets = dict((ws.title, ws) for ws in book.worksheets)

df_merge.to_excel(writer, "ETP",startcol=0,startrow=6)
writer.save()
input("Test")

【讨论】:

  • 我尝试使用您的代码,但它也不起作用,没有任何反应!
  • @FaziaChenna你可以提供更多关于你的操作系统,python版本和excel版本的信息,为什么在我的电脑上它可以正常工作
  • 我在我的问题中添加了相关信息
  • 你对 xlwings 有什么建议吗?
  • @FaziaChenna 我添加了更多信息.. 请检查。
猜你喜欢
  • 2012-10-19
  • 2014-01-14
  • 2014-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多