I'm using VBA in Excel with the amazing VBA-Tools by Tim Hall and I'm able to do pretty much everything trello related, create card, list, comments, etc
What's been frustating to me the last couple of days is that I cannot put a value in the custom field of a card, I tried everything I can think of
This is the code
Sub atualizaCustomField(listaNome As String, cardNome As String, idCF As String, valor As String)
Dim Client As New WebClient
Client.BaseUrl = "https://api.trello.com/1/"
Dim Request As New WebRequest
Request.ContentType = "application/json"
Request.Method = WebMethod.HttpPut
Request.Resource = "cards/{idCard}/customField/{idCustomField}/item"
Request.AddUrlSegment "idCard", pegaIDCard(listaNome, cardNome)
Request.AddUrlSegment "idCustomField", idCF
Request.AddQuerystringParam "key", ApplicationKey
Request.AddQuerystringParam "token", UserToken
Debug.Print Request.FormattedResource
Dim Response As WebResponse
'Set Response = Client.Execute(Request)
Set Response = Client.PostJson(Client.BaseUrl & Request.FormattedResource, valor)
Debug.Print valor
Debug.Print Response.StatusCode & ": " & Response.Content
End Sub
What's different about this is that you have to post a JSON and not simply make the request like everything else, must match this example (from trello developer site):
{
"value": {
"text": "<string>"
}
}
in my code the variable "valor" holds this string.
I know this was 9 months ago, but I ran into the same issue and found a solution that may be useful to others.
As the OP said, the "value" field needs to have json formatting and be placed in the request body. This is achieved by passing a Dictionary type to the .AddBodyParameter method.
Dim body as Object
Set body = New Dictionary
body.Add "text", "<string>"
Request.AddBodyParameter "value", body
Related
Currently, I am developing a web service which going to be called post JSON. It works fine and I got my records posted without any issue.
My issue is to display the response. I used UploadData to send .. Do I need to use download data to receive? What if I need to show in the response in MessageBox.
Note that I am expecting a response in JSON format as well. Let me know at least the concept ? First I guess, I need to receive the response and I will deserialize it.
Here is my current code. Working fine but I can't show the response.
Public Function postData(ByVal JsonBody As String) As Boolean
Dim webClient As New WebClient()
Dim resByte As Byte()
Dim resString As String
Dim reqString() As Byte
Try
Dim APIusername As String = "XXXXX"
Dim APIPassword As String = "XXXXX"
webClient.Headers("content-type") = "application/json"
webClient.Credentials = New System.Net.NetworkCredential(APIusername, APIPassword)
reqString = Encoding.Default.GetBytes(JsonBody)
resByte = webClient.UploadData(Me.urlToPost, "post", reqString)
resString = Encoding.Default.GetString(resByte)
Console.WriteLine(resString)
' Here I need to show the responses
webClient.Dispose()
Return True
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Return False
End Function
I have used http request instead of web client and it works.
I have the following JSON code that I want to post to an API (specifically discord webhook) using VBA in word.
"color":0x7289da,
"fields":[
{
"name":"**Foo**",
"value":var1,
"inline":true
},
{
"name":"**Bar**",
"value":var2,
"inline":true
},
{
"name":"**baz**",
"value":"qux",
"inline":false
}
],
"footer":{
"text":"foobar"
}
}
I want to replace var1 and var2 in the json with their respective string variables values var1 and var2 respectively when sending the request. Code for the variables:
Private Sub login_button_label_Click()
Dim var1 As String
Dim var2 As String
var1 = login.foo.Text
var2 = login.bar.Text
End Sub
The above code gets the value from 2 textboxes in a userform.
How can I post this json request to a particular link/webhook?
Solved my own question, I won't go into detail (since I don't fully understand it) but this is a sample of code for anyone who needs to post JSON to an API. For this example, I posted to discord webhook.
Dim objHTTP As Object
Dim Json As String
Json = "{""content"":""Howdy partner!"",""embeds"":null}"
Dim result As String
Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
URL = "https://discord.com/api/webhooks/guildid/webhookid"
objHTTP.Open "POST", URL, False
objHTTP.setRequestHeader "Content-type", "application/json"
objHTTP.send (Json)
result = objHTTP.responseText
Set objHTTP = Nothing
Replace the URL with your URL and edit the JSON as you would like, note JSON requires double quotes so you would need to do something like that.
If you need to incorporate variables in the JSON code, here's an example:
Dim VARIABLE as String
VARIABLE = "Howdy!"
Json = "{""content"":""" & VARIABLE & """,""embeds"":null}"
Needs NO external library. Pure VBA.
this is the code I use to call parseJson in vba and in one case where I have a JSON object, I am receiving the error 10001 which relates to the latest Json-vba library 2.2.3 when the "{" or the "[" are expected.
Sub jsontest()
Dim http As Object
Set http = CreateObject("MSXML2.XMLHTTP")
'http.Open "GET", "https://bin.codingislove.com/document/ayequrimiy", False
http.Open "GET", "https://bin.codingislove.com/ayequrimiy.json", False
http.send
MsgBox (ParseJson(http.responseText)("Count"))
End Sub
The second .json file shows the 10001 error but the first one, the same file in text form, is perfectly executing. I tried as well including brackets when I call the json string without success.
What should I correct in my parser call?
Using developer tools with call to your second url https://bin.codingislove.com/ukiyerovow.json, it can be seen that the json is returned from url https://bin.codingislove.com/documents/ukiyerovow like this:
{
"data":
"{
\"Count\":1,
\"results\":
[
{
\"showEmailIcon\":true,
\"showIcon\":true,
\"middleName\":\"\",
\"dateActivated\":1513000,
\"regAffiliateRebate\":\"No Rebate(0)\",
\"Id\":1,
\"dateLastLogin\":1513248842000,
\"countryName\":\"France\",
\"address\":null,
\"name\":\"cien\",
\"id\":1786511,
\"state\":null
}
],
\"resultClass\":\"com.zoho.dao.dto\"
}",
"key":"ayequrimiy"
}
Using Json-vba library this strign can be parsed like this. HTH
Sub jsontest()
Dim http As Object
Set http = CreateObject("MSXML2.XMLHTTP")
' use this url instaed:
Const url As String = "https://bin.codingislove.com/documents/ayequrimiy"
http.Open "GET", url, False
http.send
Dim parsedJson As Dictionary
Set parsedJson = JsonConverter.ParseJson(http.responseText)
Dim data As String
data = parsedJson("data")
Dim parsedData As Dictionary
Set parsedData = ParseJson(data)
MsgBox parsedData("Count")
End Sub
What should I correct in my parser call?
You have to correct the url. The second url should be https://bin.codingislove.com/documents/ayequrimiy. There is the json data.
Compare:
https://bin.codingislove.com/ayequrimiy.json
https://bin.codingislove.com/documents/ayequrimiy
To get e.g. Name you have to use the results which contains array so first point to the element of the array using index e.g. (1) and then take the element ("Name"):
Debug.Print parsedData("reports")(1)("Name")
Since this isn't a JSON response, you will have to make it one before you can a parse it as such. The easiest approach is to load the DOM of the page, and then extract the text.
There are lots of snippets on SO (here's one) that'll do just that.
Once you have the DOM, do something like this:
json = doc.getElementById("box").innerText
I am coding vba to open the central bank's website and input the values and extract the data, I usually do this on the mail site, bank of Brazil etc ...
() of the central bank
I can not give the input value via vba in the textbox I've already tried:
Ie.Document.all.Item("valueConverter").Innertext="1"
Ie.Document.getElementById("valueConverter").Value="1"
Ie.Document.getElementById("valueConverter")(0).Value="1"
Ie.Document.getElementByName("valueConverter").Value = "1"
The Elements of this site is this:
<Input type = "text" name = "valueConverter" maxlength = "17" size "20" value onkeypress = "return (MascaraMoeda (this, '.', ',', Event)
Does anyone know how?
tl;dr;
I cannot mark this as a duplicate as there is no accepted answer to where I posted an answer to a similar question.
Not sure of the protocol as simply posting a link in the comments doesn't mean it will be found again.
My full answer is here: Excel Web Query Submit Issues
To summarize:
You can use the bcb.gov.br Open Data Portal.
Send a request for a JSON response with the conversion rates from their Exchange rates – daily bulletins.
With the received response, amongst other methods, you can then:
Use the JSON Converter .basa and set the convert the response into a JSON object and work with that
Parse the response as a string with a regex to get the values
For brevity, I will give you just the second method here and you can view my other answer for both methods:
Public Sub GetInfo2()
Dim strURL As String, strJSON As String, item As Variant, http As Object, json As Object
Const TARGET_CURRENCY As String = "USD"
Const START_DATE As String = "06-13-2018"
Const END_DATE As String = "06-13-2018"
strURL = "https://olinda.bcb.gov.br/olinda/service/PTAX/version/v1/odata/ExchangeRatePeriod(moeda=#moeda,dataInicial=#dataInicial,dataFinalCotacao=#dataFinalCotacao)?%40moeda=%27" & TARGET_CURRENCY & "%27&%40dataInicial=%27" & START_DATE & "%27&%40dataFinalCotacao=%27" & END_DATE & "%27&%24format=json"
Set http = CreateObject("MSXML2.XMLHTTP")
http.Open "GET", strURL, False
http.send
strJSON = http.responseText
Dim Matches As Object
With CreateObject("VBScript.RegExp")
.Global = True
.MultiLine = True
.IgnoreCase = False
.Pattern = """cotacaoCompra"":\d{1,}.\d{1,}" 'The pattern I really wanted, "(?<=""cotacaoCompra"":)\d{1,}.\d{1,}", doesn't appear to be supported
If Not .test(strJSON) Then Exit Sub
Set Matches = .Execute(strJSON)
Dim match As Object
For Each match In Matches
Debug.Print Replace(match, """cotacaoCompra"":", vbNullString)
Next
End With
End Sub
I want to POST some JSON with some VBA:
Dim sURL As String, sHTML As String, sAllPosts As String
Dim oHttp As Object
Dim blWSExists As Boolean
Set oHttp = CreateObject("MSXML2.XMLHTTP")
sURL = "some webste.com"
oHttp.Open "POST", sURL, False
oHttp.setRequestHeader "Content-type", "application/json"
oHttp.setRequestHeader "Accept", "application/json"
oHttp.Send (mType = OPEN_SYSTEM_TRADE & systemOwnerId = 10)
sHTML = oHttp.ResponseText
Worksheets("Open1").Range("A1").Value = sHTML
The predefined format to be sent to the website is a description in json as follows :
{"mType":"OPEN_SYSTEM_TRADE","systemOwnerId":10,"systemId":16, etc}
My oHttp.Send line must be wrong, as soon as i add more arguments, i get a compiler error
I publish this (not working) code cause its the best i could find on the web so far (all other get me stuck on other things that i don't understand ...
I also tried to put the json code in a cell, put the cell in a string, and send the string like this : oHttp.Send (string), which results in a Error 406 Not Acceptable reply from the website.
JSON can be very sensitive to how it's formatted, so I would make sure everything is quoted properly before it is sent. I would recommend splitting Body into a separate variable and debugging the value with http://jsonformatter.curiousconcept.com/ before sending.
Dim Body As String
Body = "{""mType"":""OPEN_SYSTEM_TRADE"",""systemOwnerId"":10}"
' Set breakpoint here, get the Body value, and check with JSON validator
oHttp.Send Body
I ran into many similar issues when working with Salesforce's REST API and combined my work into a library that may be useful to you: https://github.com/VBA-tools/VBA-Web. Using this library, your example would look like:
Dim Body As New Dictionary
Body.Add "mType", "OPEN_SYSTEM_TRADE"
Body.Add "systemOwnerId", 10
Dim Client As New WebClient
Dim Response As WebResponse
Set Response = Client.PostJson("somewebsite.com", Body)
Worksheets("Open1").Range("A1").Value = Response.Content