Mac 上的Shell() VBA 函数似乎需要将完整路径作为 HFS 样式路径(使用冒号而不是斜杠)。它似乎也不像在 Windows 上那样接受参数(如果添加了任何参数,则会报告“找不到路径”错误)。
也可以使用MacScript() VBA 函数:MacScript("do shell script ""command""")。这可能是最简单的选择,也是我建议做的。缺点是它有相当多的开销(每次调用 100-200 毫秒)。
另一种选择是标准 C 库中的 system() 函数:
Private Declare Function system Lib "libc.dylib" (ByVal command As String) As Long
Sub RunSafari()
Dim result As Long
result = system("open -a Safari --args http://www.google.com")
Debug.Print Str(result)
End Sub
有关文档,请参阅 http://pubs.opengroup.org/onlinepubs/009604499/functions/system.html。
system() 只返回退出代码。如果你想得到命令的输出,你可以使用popen()。
Private Declare Function popen Lib "libc.dylib" (ByVal command As String, ByVal mode As String) As Long
Private Declare Function pclose Lib "libc.dylib" (ByVal file As Long) As Long
Private Declare Function fread Lib "libc.dylib" (ByVal outStr As String, ByVal size As Long, ByVal items As Long, ByVal stream As Long) As Long
Private Declare Function feof Lib "libc.dylib" (ByVal file As Long) As Long
Function execShell(command As String, Optional ByRef exitCode As Long) As String
Dim file As Long
file = popen(command, "r")
If file = 0 Then
Exit Function
End If
While feof(file) = 0
Dim chunk As String
Dim read As Long
chunk = Space(50)
read = fread(chunk, 1, Len(chunk) - 1, file)
If read > 0 Then
chunk = Left$(chunk, read)
execShell = execShell & chunk
End If
Wend
exitCode = pclose(file)
End Function
Sub RunTest()
Dim result As String
Dim exitCode As Long
result = execShell("echo Hello World", exitCode)
Debug.Print "Result: """ & result & """"
Debug.Print "Exit Code: " & str(exitCode)
End Sub
请注意,以上示例中的几个Long 参数是指针,因此如果发布了 64 位版本的 Mac Word,则必须进行更改。