我在Mac上使用Excel 2016。在VBA脚本中,我有
Private Declare PtrSafe Function popen64 Lib "libc.dylib" Alias "popen" (ByVal command As String, ByVal mode As String) As LongPtr
Private Declare PtrSafe Function pclose64 Lib "libc.dylib" Alias "pclose" (ByVal file As LongPtr) As Long
Private Declare PtrSafe Function fread64 Lib "libc.dylib" Alias "fread" (ByVal outStr As String, ByVal size As LongPtr, ByVal items As LongPtr, ByVal stream As LongPtr) As Long
Private Declare PtrSafe Function feof64 Lib "libc.dylib" Alias "feof" (ByVal file As LongPtr) As LongPtr
' @internal
Public Type ShellResult
Output As String
ExitCode As Long
End Type
Public Function ExecuteInShell(command As String) As ShellResult
Dim result As LongPtr
Dim chunk As String
Dim read As Long
result = popen64(command, "r")
If result = 0 Then
' TODO Investigate why this could happen and what should be done if it happens
Exit Function
End If
Do While feof64(result) = 0
chunk = VBA.Space$(50)
read = fread64(chunk, 1, Len(chunk) - 1, result)
If read > 0 Then
chunk = VBA.Left$(chunk, read)
ExecuteInShell.Output = ExecuteInShell.Output & chunk
End If
Loop
cleanup:
ExecuteInShell.ExitCode = pclose64(result)
End Function
Sub Process_Click()
Dim result As ShellResult
result = ExecuteInShell("echo $SHELL & whoami & echo $PATH & pwd")
Debug.Print (result.Output)
End Sub
运行Process_Click时,我看到以下内容:
/bin/bash
/Users/tim/Library/Containers/com.microsoft.Excel/Data
/usr/bin:/bin:/usr/sbin:/sbin
tim
请注意顺序是奇怪的,就像每个命令都在单独的线程上运行一样(这可能暗示我做错了!)。我想运行/ usr / local / bin中的程序(rscript)。但是,如果我运行ExecuteInShell("/usr/local/bin/rscript")
,则不会得到任何输出。同样奇怪的是,如果我ExecuteInShell("ls")
看到正确的内容,但是如果我ExecuteInShell("ls /usr/local/bin")
则会得到空白的结果。也许有一些逃避问题?
TL; DR。我需要将/usr/local/bin
添加到我的popen $ PATH中,或者使用/usr/local/bin/rscript
调用我的脚本,但是我不能!非常感谢您的协助。