首页 > 解决方案 > 试图从 VBA 调用 python 脚本

问题描述

我需要使用 VBA 从 Excel 宏中调用 python 脚本。我收到一条错误消息“对象 iwshshell3 的方法运行失败”并且无法弄清楚原因。

我尝试过编辑路径、重新下载 Spyder 等。

Option Explicit
Sub Test()
  Dim objShell As Object
  Dim PythonExe, PythonScript As String
  Set objShell = VBA.CreateObject("Wscript.Shell")
  PythonExe = "C:\Users\Frydman\AppData\Local\Programs\Python\Python37-32\python.exe"
  PythonScript = "C:\Users\Frydman\.spyder-py3\temp.py"
  objShell.Run PythonExe & PythonScript
End Sub

这是我的 VBA 代码不起作用

我收到错误消息:

“对象 iwshshell3 的方法运行失败”。

我希望我的 python 代码在我调用存储此 VBA 代码的宏后运行。

标签: pythonexcelvba

解决方案


这是一个在 VB 中调用 python 的示例,来自http://docs.xlwings.org/en/v0.6.4/index.html的文档页面

Sub MyMacro()
    RunPython ("import mymodule; mymodule.rand_numbers()")
End Sub

然后在你的python脚本中

import numpy as np
from xlwings import Workbook, Range

def rand_numbers():
    """ produces std. normally distributed random numbers with shape (n,n)"""
    wb = Workbook.caller()  # Creates a reference to the calling Excel file
    n = int(Range('Sheet1', 'B1').value)  # Write desired dimensions into Cell B1
    rand_num = np.random.randn(n, n)
    Range('Sheet1', 'C3').value = rand_num

推荐阅读