简体   繁体   English

在POST请求VBA Excel中发送数组字符串

[英]Send an array string inside POST Request VBA Excel

I'm trying to send a post request to an API that takes an array of strings as an argument .我正在尝试向将字符串数组作为参数的 API 发送 post 请求

It comes out an error specifying that the types are not allowed and when the request is sent correctly all the data is left in the first position of the array (keyArray[0]).它出现一个错误,指出类型是不允许的,当请求正确发送时,所有数据都留在数组的第一个位置 (keyArray[0])。

The code I am using is the following:我使用的代码如下:

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)

I don't understand why you set vvArray and then vvArrayString ?我不明白你为什么先设置vvArray然后设置vvArrayString Why not go straight to vvArrayString by looping through column B?为什么不通过循环 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

That should set the array correctly for you, you can then carry on to the next bit of code (the http request).这应该为您正确设置数组,然后您可以继续执行下一段代码(http 请求)。

EDIT: the http request could also use a similar loop, as it's in such a simple repeating pattern.编辑: http 请求也可以使用类似的循环,因为它采用如此简单的重复模式。 However you'd need a separate variable for it;但是,您需要一个单独的变量;

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)

Then instead of the long previous string, you just do TCRequestItem.send(strPostReq)然后,而不是之前的长字符串,您只需执行TCRequestItem.send(strPostReq)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM