问题描述
我正在尝试将发布请求发送到以字符串数组作为参数的API 。
出现错误,指出不允许使用这些类型,并且正确发送请求后,所有数据都将保留在数组的第一位置(keyArray [0])。
我正在使用的代码如下:
Dim lastRow As Variant
lastRow = Range("B" & Rows.Count).End(xlUp).Row
Dim vvArray As Variant
vvArray = Range("B12:B" & lastRow).Value
Dim vvArrayString() As String
ReDim vvArrayString(1 To UBound(vvArray))
For i = 1 To UBound(vvArray)
vvArrayString(i) = vvArray(i,1)
Next
Dim TCRequestItem As Object
Set TCRequestItem = CreateObject("WinHttp.WinHttpRequest.5.1")
TCRequestItem.Open "POST","url",False
TCRequestItem.setRequestHeader "Content-type","application/x-www-form-urlencoded"
TCRequestItem.send ("keyArray=" + vvArrayString)
解决方法
我不明白您为什么先设置vvArray
然后再设置vvArrayString
?为什么不通过遍历B列直接进入vvArrayString
?
Dim LastRow as Long
LastRow = Range("B" & Rows.Count).End(xlUp).Row
Dim vvArrayString(1 to LastRow-11)
For i = 12 to LastRow
vvArrayString(1-11) = Range("B" & i).text
Next
这应该为您正确设置数组,然后您可以继续执行下一部分代码(http请求)。
编辑:http请求也可以使用类似的循环,因为它的重复方式很简单。但是,您需要一个单独的变量;
Dim strPostReq as String 'here's your separate variable
For x = 1 to LastRow-11
'Just add the same pattern to the end of the string each time
strPostReq = strPostReq & "keyArray[" & x-1 & "]=" & vvArrayString(x) & "&"
Next
'Then remove the last '&' from the string
strPostReq = Left(strPostReq,Len(strPostReq) - 1)
然后,您只需执行TCRequestItem.send(strPostReq)