[英]How can I run Python commands from within Excel VBA?
我正在努力從Excel VBA(我熟悉)訪問Python。 這里有一個非常有用的答案(轉載如下)。 我非常仔細地遵循了這些步驟-無論我使用的是Python 3.3還是Python 2.7,都會發生相同的錯誤。
當我使用命令按鈕執行VBA代碼時,它在以下語句中失敗:PyScript.Language =“ python”,並出現錯誤消息“運行時錯誤380:無法創建用於指定語言的腳本引擎”
有什么想法嗎?
我嘗試使用的stackoverflow的答案如下。
請仔細執行以下步驟
安裝完成后,打開命令提示符並轉到
C:\\ Python25 \\ LIB \\站點包\\ win32comext \\ axscript \\客戶端
執行\\> python pyscript.py
您應該看到消息已注冊:Python
轉到MS Office Excel並打開工作表
切換到代碼編輯器並插入以下代碼
昏暗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。 我只是按照說明的步驟進行操作,只是為了簡化起見,我沒有創建用戶窗體或按鈕,而是從dim語句中刪除了“ WithEvents”,並將子控件設為Public(請參見下文)。 使用Alt-F8在工作表中運行宏,它可以正常工作。
我也在Excel 2013中對其進行了測試,沒有問題。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.