python - 试图从 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 代码的宏后运行。
解决方案
这是一个在 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
推荐阅读
- javascript - 没有使用 Avahi/Zeroconf (machineName.local) 的 Service Worker
- mecab - 为什么会发生运行时错误?导入 Mecab 后
- php - Wordpress中标签的不同颜色?
- flutter - 将小部件扩展到列表视图中的父项
- mysql - MySQL选择24小时内不需要得分轨迹行的不同玩家
- r - 如何用负坐标和正坐标计算R中点之间的距离
- python-3.x - Python3从字符串创建一个UTC日期
- node.js - 如何在heroku中指定节点版本
- javascript - 创建面积图:带有 NaN 的路径
- dart - 在未来返回中制作“Navigator.push”