How do I issue an HTTP GET from Excel VBA for Mac

前端 未结 3 1126
庸人自扰
庸人自扰 2020-11-29 04:28

I need to issue an HTTP Get with a query string to a web service from Excel for Mac 2011. I\'ve seen the answers for using QueryTables (How can I send an HTTP POST request

3条回答
  •  时光取名叫无心
    2020-11-29 04:36

    The answer above from John Stephens is fantastic (please upvote it!), but it no longer worked for me in the more recent Excel:mac 2016, with an error that the code needs to be updated for use on 64-bit systems.

    Taking some tips from an issue I found in a related repository, I was able to adjust the data types in John's script to work correctly in Excel:mac 2016:

    Option Explicit
    
    ' execShell() function courtesy of Robert Knight via StackOverflow
    ' http://stackoverflow.com/questions/6136798/vba-shell-function-in-office-2011-for-mac
    
    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
    
    Function HTTPGet(sUrl As String, sQuery As String) As String
    
        Dim sCmd As String
        Dim sResult As String
        Dim lExitCode As Long
    
        sCmd = "curl --get -d """ & sQuery & """" & " " & sUrl
        sResult = execShell(sCmd, lExitCode)
    
        ' ToDo check lExitCode
    
        HTTPGet = sResult
    
    End Function
    

提交回复
热议问题