Excel vba call Python script on Mac

How can I launch an external python process from Excel 365 VBA on OSX?

It took me a while, but I figured out how to do it.

Excel 2016 has replaced MacScript() with AppleScriptTask(). This needs to be given an AppleScript file and function to call, and can't, as far as I am aware, be given raw AppleScript commands.

I created an AppleScript file called PythonCommand.scpt which contained something like:

on PythonCommand(pythonScript)
do shell script "/usr/local/bin/python " & pythonScript
end PythonCommand
This AppleScript file needs to be then placed in ~/Library/Application Scripts/com.microsoft.Excel/ (create this folder if it doesn't exist)

Once this is here, the function can be called using:

Dim result As String
result = AppleScriptTask("PythonCommand.scpt", "PythonCommand", pythonScript)
(it insists on returning something - it won't work without this)

A security proviso:

Any Excel macro can call this AppleScript. Macros can do nasty things anyway, but it would be worth putting some protection into it anyway to avoid additional code being executed.


翻译成人话:

mkdir -p ~/Library/Application\ Scripts/com.microsoft.Excel
vim PythonCommand.scpt

i输入以下内容

on PythonCommand(pythonScript)
	do shell script "python -c '" & pythonScript & "'"
end PythonCommand

保存
然后在 Excel 新建一个 vba 模块

Sub CallPython()
    s = AppleScriptTask("PythonCommand.scpt", "PythonCommand", "print(42)")
    MsgBox (s)
End Sub

执行

have fun!

posted on 2020-11-06 20:50  明天有风吹  阅读(472)  评论(0编辑  收藏  举报

导航

+V atob('d2h5X251bGw=')

请备注:from博客园