Calling python script from excel/vba

后端 未结 6 989
一个人的身影
一个人的身影 2020-11-28 05:48

I have a python code that reads 3 arguments (scalars) and a text files and then returns me a vector of double. I want to write a macro in vba to call this python code and wr

6条回答
  •  误落风尘
    2020-11-28 06:24

    Follow these steps carefully

    1. Go to Activestate and get ActivePython 2.5.7 MSI installer.
      I had DLL hell problems with 2.6.x
    2. Install in your Windows machine
    3. once install is complete open Command Prompt and go to

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

    4. execute \> python pyscript.py you should see message Registered: Python

    5. Go to ms office excel and open worksheet

    6. Go to Tools > Macros > Visual Basic Editor
    7. Add a reference to the Microsoft Script control alt text
    8. Add a new User Form. In the UserForm add a CommandButton
    9. Switch to the code editor and Insert the following code

      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
      

    Execute. Enjoy and expand as necessary

提交回复
热议问题