且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从Excel VBA for Mac 2011发出HTTP GET

更新时间:2023-10-10 22:05:52

进一步研究,我遇到了Robert Knight对这个问题的评论 Office 2011 for Mac中的VBA Shell功能,并使用他的execShell函数构建了一个HTTPGet函数来调用卷曲。我在Mac上运行Mac OS X 10.8.3(Mountain Lion)的Mac测试了这个。这是VBA代码:

 code> Option Explicit 

'execShell()函数由Robert Knight通过***
'https://***.com/questions/6136798/vba-shell-function-in -office-2011-for-mac

私有声明函数popen Liblibc.dylib(ByVal命令As String,ByVal mode As String)As Long
私有声明函数pclose Liblibc .dylib(ByVal文件As Long)As Long
私有声明函数fread Liblibc.dylib(ByVal outStr As String,ByVal size As Long,ByVal items As Long,ByVal stream As Long)As Long
私有声明函数feof Liblibc.dylib(ByVal file As Long)As Long

函数execShell(命令As String,可选ByRef exitCode As Long)As String
Dim file As Long
file = popen(command,r)

如果file = 0然后
退出函数
如果

feof(file)= 0
Dim chunk As String
Dim read As Long
chunk = Space(50)
read = fread(chunk,1,Len(chunk) - 1,file)
如果读取> 0然后
chunk = Left $(chunk,read)
execShell = execShell& chunk
End If
Wend

exitCode = pclose(file)
结束函数

函数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检查lExitCode

HTTPGet = sResult

结束函数
要使用此功能,请复制上述代码,打开Excel for Mac 2011中的VBA编辑器。如果您没有一个模块,单击插入 - >模块。将代码粘贴到模块文件中。离开VBA编辑器(clover-Q)。

这是一个使用天气预报网络服务的具体示例( http://openweathermap.org/wiki/API/JSON_API



单元格A1将被保留对于城市的名称。



在单元格A2中,输入URL字符串: http://api.openweathermap.org/data/2.1 / forecast / city