在POST请求VBA Excel中发送数组字符串
我正在尝试向API发送post请求,该API将字符串数组作为参数 出现一个错误,指定不允许使用类型,并且当请求正确发送时,所有数据都保留在数组的第一个位置(keyArray[0]) 我使用的代码如下所示:在POST请求VBA Excel中发送数组字符串,excel,vba,winhttp,winhttprequest,Excel,Vba,Winhttp,Winhttprequest,我正在尝试向API发送post请求,该API将字符串数组作为参数 出现一个错误,指定不允许使用类型,并且当请求正确发送时,所有数据都保留在数组的第一个位置(keyArray[0]) 我使用的代码如下所示: Dim lastRow As Variant lastRow = Range("B" & Rows.Count).End(xlUp).Row Dim vvArray As Variant vvArray = Range("B12:B" &
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
,然后设置vvarraysting
?为什么不直接通过循环B列进入vvaraystring
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(strpstreq)
而不是前面的长字符串,当您对代码执行F8时,它在哪里中断?给出了一个编译错误,表示不允许使用类型,问题出在代码的最后一行TCRequestItem.send(“keyrarray=“+vvaraystring”)
。我尝试过这样做,但它确实有效,但我认为必须有另一种方法:TCRequestItem.send(“keyArray[0]=”+vvArrayString(1)+“&keyArray[1]=”+vvArrayString(2)+……)
在错误恢复下一步时
:)对于下一位代码,我尝试过这样做,并且它有效TCRequestItem.send(“keyArray[0]=”+vvArrayString(1)+“&keyArray[1]=”+vvArrayString(2)+……)
也许声明一个返回该字符串的函数可以解决这个问题……看起来您可以使用另一个循环来解决这个问题?耐心点,我会把它编辑成我的答案