如何在VBA中调用Python脚本

Python020

如何在VBA中调用Python脚本,第1张

已有一个Python脚本实现了部分功能,想使用VBA直接调用Python脚本

Python脚本如下:

[python] view plain copy

import time

def hello(name):

return "Hello, " + name + "!"

print hello("World")

#延时关闭windows控制台,使得用户可以看到运行结果

time.sleep(150)

方法如下:

[python] view plain copy

<pre name="code" class="vb">Sub test()

Call Shell("C:\Python27\Python.exe C:\Users\Hongxing\Desktop\py2exe\Hello.py", vbNormalFocus)

End Sub

#需要先安装pipywin32模块

class PythonUtilities:

_public_methods_=['SplitString']

_reg_progid_='PythonDemos.Utilities'

# 使用"print (pythoncom.CreateGuid())" 得到一个自己的clsid,不要用下面这个!!

_reg_clsid_='{5FCAC95E-653A-484C-8568-A02D5E0256E8}'

def SplitString(self, val, item=None):

import string

if item !=None: item=str(item)

val=str(val)

return val.split(item)

if __name__=='__main__':

print ('Registering COM server...')

import win32com.server.register

win32com.server.register.UseCommandLine(PythonUtilities)

下面是VB的相关代码:

Private Sub Form_Load()

Set PythonUtils = CreateObject("PythonDemos.Utilities")

response = PythonUtils.SplitString("Hello from VB")

For Each Item In response

MsgBox Item

Next

End Sub

完成后在cmd中使用(py_name是上面python文件的名称)

>python py_name.py --unregister