Используйте VBA-Web для отправки значения ячейки как тела - PullRequest
0 голосов
/ 25 сентября 2019

Я смотрю на VBA-Web, полезный скрипт для использования Excel для создания веб-запросов.Это некоторый POST-код:

Dim Client As New WebClient
Client.BaseUrl = "https://api.testing.com/"

Dim Request As New WebRequest
Request.Resource = "pages"
Request.Method = WebMethod.HttpPost

' Formatting
' ---------- '
' Simple: Request.Format sets four things:
'         1. Content-Type header
'         2. Accept header
'         3. Request Body conversion
'         4. Response Data conversion
Request.Format = WebFormat.Json

' Medium: Set separate request and response format
Request.RequestFormat = WebFormat.Json ' Set Content-Type and request converter
Request.ResponseFormat = WebFormat.Json ' Set Accept and response converter

' Advanced: Set separate everything
Request.RequestFormat = WebFormat.Json
Request.ContentType = "application/json"
Request.ResponseFormat = WebFormat.Json
Request.Accept = "application/json"

' Body
' ---- '
' a. Add body as string
Request.Body = "{""a"":123,""b"":[456, 789]}"

' b. Add parameters (converted with RequestFormat)
Request.AddBodyParameter "a", 123
Request.AddBodyParameter "b", Array(456, 789)
' -> Request.Body (for json): "{""a"":123,""b"":[456, 789]}"

' c. Add body as dictionary (or Collection or Array)
Dim Body As New Dictionary
Body.Add "a", 123
Body.Add "b", Array(456, 789)
Set Request.Body = Body
' -> Request.Body (for json): "{""a"":123,""b"":[456, 789]}"

' Add other things common to all Requests
Request.AddCookie "cookie", "abc"
Request.AddHeader "header", "def"
Request.AddQuerystringParam "querystring", "ghi"
' etc.

' To debug the request:
' 1. From VBA, Open Immediate Window (View > Immediate Window or Ctrl + g)
' 2. Type: RestHelpers.EnableLogging = True
' 3. Run request

' Make the request
Dim Response As WebResponse
Set Response = Client.Execute(Request)

' POST https://api.testing.com/pages?querystring=ghi
' header: def
' User-Agent: Excel Client v3.1.4 (https://github.com/timhall/Excel-REST)
' Content-Type: application/json
' Accept: application/json
' Content-Length: 23
' Cookie: cookie=abc
'
' {"a":123,"b":[456,789]}

' Handle the response
If Response.StatusCode = WebStatusCode.Created Then
    ' ...
End If

Однако я нигде не вижу в документации, как бы я взял значение из ячейки, например, ячейки A1 и B1, и отправил бы это как JSON.

Кажется, что это возможно, но, кажется, только жестко закодировать значения тела.

1 Ответ

1 голос
/ 25 сентября 2019

Пример может быть следующим:

Request.Body = ThisWorkbook.Worksheets("Sheet1").Range("A1").value
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...