【问题标题】:Send an array string inside POST Request VBA Excel在 POST 请求 VBA Excel 中发送数组字符串
【发布时间】:2020-09-24 06:42:14
【问题描述】:

我正在尝试向以字符串数组作为参数的 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)

【问题讨论】:

  • 当你F8通过代码时,它在哪里中断?
  • 给我一个编译错误,说不允许类型,问题出在代码的最后一行TCRequestItem.send ("keyArray=" + vvArrayString)
  • 我已经尝试过这样做并且它有效,但我认为必须有另一种方法来获得它:TCRequestItem.send ("keyArray[0]=" + vvArrayString(1) + "&keyArray[1]=" + vvArrayString(2) + ...)
  • on error resume next :)

标签: excel vba winhttp winhttprequest


【解决方案1】:

我不明白你为什么设置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)

,而不是之前的长字符串

【讨论】:

  • 对于下一段代码,我尝试这样做并且它可以工作TCRequestItem.send ("keyArray[0]=" + vvArrayString(1) + "&keyArray[1]=" + vvArrayString(2) + ...) 也许声明一个返回该字符串的函数可以解决问题...
  • 看起来您可以为此使用另一个循环?请耐心等待,我会将其编辑到我的答案中
猜你喜欢
  • 1970-01-01
  • 2016-03-28
  • 1970-01-01
  • 2014-09-26
  • 2018-09-19
  • 1970-01-01
  • 2017-07-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多