Fra*_*ave 15 macos shell vba excel-vba-mac
我试图从Word 2011 for Mac中的VBA宏启动一个shell脚本,该脚本将在终端窗口中运行.我尝试过使用Shell函数和MacScript函数,但在任何一种情况下,VBA解释器似乎都无法找到该脚本.
根据VBA参考文档,以下内容应该有效:
RetVal = Shell("Macintosh HD:Applications:Calculator.app", vbNormalFocus)
Run Code Online (Sandbox Code Playgroud)
这会产生运行时错误53'找不到文件'.
有什么建议?
Rob*_*ght 18
Shell()Mac上的VBA功能似乎需要完整路径作为HFS样式路径(使用冒号而不是斜线).它似乎也不像在Windows上那样接受参数(如果添加了任何参数,则报告"未找到路径"错误).
该MacScript()VBA功能也可用于:MacScript("do shell script ""command""").这可能是最简单的选择,我建议做什么.缺点是它有很多开销(每次通话100-200ms).
另一种选择是system()标准C库中的函数:
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
Run Code Online (Sandbox Code Playgroud)
有关文档,请参见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
Run Code Online (Sandbox Code Playgroud)
请注意,上例中的几个Long参数是指针,因此如果发布64位版本的Mac Word,则必须更改.
| 归档时间: |
|
| 查看次数: |
19811 次 |
| 最近记录: |