Shell call from Excel VBA freezes - involves MacSc

2019-08-29 12:28发布

This macro runs fine on Excel 2011 for Mac:

Sub Works()
    scriptToRun = "do shell script ""/anaconda/bin/python -c "" & quoted form of ""import test_file"" "
    res = MacScript(scriptToRun)
    Debug.Print res
End Sub

The according test_file.py file (place it somewhere on the pythonpath) is:

import sys
print(sys.version)

However, when I involve the appscript Python package, it freezes for a very long time and does nothing. Change the test_file.py file to this (pip install appscript first):

import appscript
app = appscript.app('Microsoft Excel')
app.cells['A1'].value.set(2)

But when I run the command directly from the AppleScript Editor, this works:

do shell script "/anaconda/bin/python -c " & quoted form of "import test_file"

How can I call this from Excel VBA on Mac? (By the way on Windows, it works easily with WScript.Shell and pywin32)

1条回答
姐就是有狂的资本
2楼-- · 2019-08-29 12:45

The solution was to use the system()/popen() call from this answer and run the command as background process with an ampersand at the end:

Private Declare Function system Lib "libc.dylib" (ByVal command As String) As Long

Sub RunTest()
    Dim result As String
    result = system("/anaconda/bin/python -c 'import test_file' &")
End Sub
查看更多
登录 后发表回答