2

我正在努力从 Excel VBA(我熟悉)访问 Python。这里有一个非常有用的答案(转载如下)。我非常仔细地执行了这些步骤 - 无论我使用的是 Python 3.3 还是 Python 2.7,都会出现同样的错误。

当我使用命令按钮执行 VBA 代码时,它在以下语句中失败:PyScript.Language = "python" 并显示错误消息“运行时错误 380:无法创建指定语言的脚本引擎”

请问有什么想法吗?

我尝试使用的stackoverflow的答案如下。

仔细按照这些步骤

  1. 转到 Activestate 并获取 [ActivePython 2.5.7][1] MSI 安装程序。
    我遇到了 2.6.x 的 DLL 地狱问题
  2. 在你的 Windows 机器上安装
  3. 安装完成后打开命令提示符并转到

    C:\Python25\lib\site-packages\win32comext\axscript\client

  4. 执行\> python pyscript.py 您应该看到消息已注册:Python

  5. 转到 ms office excel 并打开工作表

  6. 转到工具 > 宏 > Visual Basic 编辑器
  7. 添加对Microsoft Script 控件的引用![alt text][2]
  8. 添加一个新的用户表单。在用户窗体中添加一个命令按钮
  9. 切换到代码编辑器并插入以下代码

    Dim WithEvents PyScript As 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
    

执行。根据需要享受和扩展

4

1 回答 1

3

I'm running 32 bit Excel 2010 and Anaconda Python 2.7. I followed the procedure exactly as stated, except to keep things simple I didn't create the user form or button, and removed the "WithEvents" from the dim statement, and made the sub Public (see below). Running the macro from the worksheet with Alt-F8, it works with no problem.

I have also tested it in Excel 2013, and had no problem.

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
于 2014-05-10T00:16:11.740 回答