2

I'm trying to run a node command with VBA in an Excel macro and with the help of this answer I came up with this:

Private Declare PtrSafe Function popen Lib "libc.dylib" (ByVal command As String, ByVal mode As String) As LongPtr
Private Declare PtrSafe Function pclose Lib "libc.dylib" (ByVal file As LongPtr) As Long
Private Declare PtrSafe Function fread Lib "libc.dylib" (ByVal outStr As String, ByVal size As LongPtr, ByVal items As LongPtr, ByVal stream As LongPtr) As Long
Private Declare PtrSafe Function feof Lib "libc.dylib" (ByVal file As LongPtr) As LongPtr

Function execShell(command As String, Optional ByRef exitCode As Long) As String
    Dim file As LongPtr
    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("node -v", exitCode)
    Debug.Print "Result: """ & result & """"
    Debug.Print "Exit Code: " & Str(exitCode)
End Sub

But when I run RunTest() I get this erroneous response:

Result: ""
Exit Code:  32512

While it should've returned something like:

Result: "v8.4.0"
Exit Code:  0

Something is going wrong, but I couldn't find any clear insight as to what is going wrong and how I could fix it. Other commands such as whoami, ls and echo work as expected when I try them.

Kid Diamond
  • 2,232
  • 8
  • 37
  • 79

0 Answers0