我如何从Excel VBA中运行Python命令?
我努力从Excel VBA(我熟悉)访问Python。 这里有一个非常有用的答案(转载如下)。 我非常小心地遵循了这些步骤 – 无论是使用Python 3.3还是Python 2.7,都会发生同样的错误。
当我使用命令button执行VBA代码时,它失败,在这条语句:PyScript.Language =“python”错误消息“运行时错误380:指定语言的脚本引擎不能创build”
有什么想法吗?
我试图使用从stackoverflow的答案如下。
请仔细按照这些步骤
- 转到Activestate并获取[ActivePython 2.5.7] [1] MSI安装程序。
我有2.6.x的DLL地狱问题 - 安装在你的Windows机器上
-
一旦安装完成,打开命令提示符并转到
C:\ Python25 \ LIB \站点包\ win32comext \ axscript \客户端
-
执行
\> python pyscript.py
你应该看到消息Registered:Python -
去ms office excel打开工作表
- 转到工具>macros> Visual Basic编辑器
- 添加对Microsoft Script控件的引用![alt text] [2]
- 添加一个新的用户表单。 在用户窗体中添加一个CommandButton
-
切换到代码编辑器并插入以下代码
Dim WithEvents PyScript作为MSScriptControl.ScriptControl
Private Sub CommandButton1_Click() If PyScript Is Nothing Then Set PyScript = New MSScriptControl.ScriptControl PyScript.Language = "python" PyScript.AddObject "Sheet", Workbooks(1).Sheets(1) PyScript.AllowUI = True End If PyScript.ExecuteStatement "Sheet.cells(1,1).value='Hello'" End Sub
执行。 享受和扩大必要的
我正在运行32位Excel 2010和Anaconda Python 2.7。 除了保持简单之外,我没有创build用户表单或button,并从dim语句中删除了“WithEvents”,并创build了Sub Public(见下文)。 使用Alt-F8从工作表中运行macros,它没有问题。
我也在Excel 2013中testing过,并没有问题。
Public Sub TestPyScript() Dim PyScript As MSScriptControl.ScriptControl If PyScript Is Nothing Then Set PyScript = New MSScriptControl.ScriptControl PyScript.Language = "python" PyScript.AddObject "Sheet", Workbooks(1).Sheets(1) PyScript.AllowUI = True End If PyScript.ExecuteStatement "Sheet.cells(1,1).value='Hello'" End Sub