我目前有一个电子表格,其中宏创建一个JSON字符串并使用HTTP将其发布到Web服务。在Windows上,此代码适用于此:
Private Sub pvPostString(sUrl As String, sString As String, sFileName As String, Optional ByVal bAsync As Boolean)
Const STR_BOUNDARY As String = "3fbd04f5-b1ed-4060-99b9-fca7ff59c113"
Dim nFile As Integer
Dim baBuffer() As Byte
Dim sPostData As String
Dim connUrl As String
sPostData = sString
'--- prepare body
sPostData = "--" & STR_BOUNDARY & vbCrLf & _
"Content-Disposition: form-data; name=""uploadfile""; filename=""" & Mid$(sFileName, InStrRev(sFileName, "\") + 1) & """" & vbCrLf & _
"Content-Type: application/octet-stream" & vbCrLf & vbCrLf & _
sPostData & vbCrLf & _
"--" & STR_BOUNDARY & "--"
'--- post
With CreateObject("MSXML2.XMLHTTP")
.Open "POST", sUrl, bAsync
.SetRequestHeader "Content-Type", "multipart/form-data; boundary=" & STR_BOUNDARY
.Send pvToByteArray(sPostData)
End With
End Sub
然而,在最新的Mac Excel上,我收到错误“ActiveX组件无法创建对象”。这是有道理的,因为MSXML2.XMLHTTP是一个Microsoft解决方案,但这意味着我需要找到一个替换函数。
我已经在这个问题上做了大量的Google搜索,从我读过的内容中我可以使用查询表来实现这一点。但是,我尝试了各种配置,但没有任何乐趣。例如,如果我尝试以下操作,那么我会收到错误“无效的网络查询”
With ActiveSheet.QueryTables.Add(Connection:=connUrl, Destination:=Range("C30"))
.PostText = myJSONString
.RefreshStyle = xlOverwriteCells
.SaveData = True
.Refresh
End With
这是有道理的,因为JSON不是有效的帖子文本,但同时发布一个冗长的JSON文件作为帖子文本似乎不是正确的解决方案。
理想情况下,我想将JSON发布为文件,以便可以通过$ _FILES []在服务器上引用它。虽然从我所读到的内容尚不清楚如何做到这一点(或者如果可能的话)。
tldr;最终我的目标是让一个函数允许我通过http发布一个冗长的JSON字符串,它可以在Windows和Mac上运行。我真的很感激任何帮助。
答案 0 :(得分:0)
VBA-Web(以前的Excel-REST)在v4.0.0中支持Mac中的Windows,并允许您从VBA获取GET,POST,PUT,PATCH和DELETE。我还没有尝试过上传文件,所以我不确定它会不会适合你的情况,但我会试一试。这是一个示例:
' Replace with the following
' With CreateObject("MSXML2.XMLHTTP")
' .Open "POST", sUrl, bAsync
' .SetRequestHeader "Content-Type", "multipart/form-data; boundary=" & STR_BOUNDARY
' .Send pvToByteArray(sPostData)
' End With
' Client for executing requests
Dim Client As New WebClient
' Generally set Client.BaseUrl here, but it's not required
' Request for setting request details
Dim Request As New WebRequest
Request.Method = WebMethod.HttpPost
Request.Resource = sUrl
Request.ContentType = "multipart/form-data; boundary=" & STR_BOUNDARY
' Execute request and store response
Dim Response As WebResponse
Set Response = Client.Execute(Request)