Calling specific variable VBA Rest API [closed] - vba

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I am struggling to understand how I can call a specific variable and organize it in an excel worksheet.
I need to get the buy, sell and vol from this url https://api.blinktrade.com/api/v1/BRL/ticker?crypto_currency=BTC but I am not able to find out how to separate it.
I am using this code to call the data
Public Sub btcteste()
'Dim xmlhttp As Object
Dim xmlhttp As New MSXML2.ServerXMLHTTP60
Set xmlhttp = CreateObject("MSXML2.serverXMLHTTP")
Dim myurl As String
myurl = "https://api.blinktrade.com/api/v1/BRL/ticker?crypto_currency=BTC"
xmlhttp.Open "GET", myurl, False
xmlhttp.send
MsgBox (xmlhttp.responseText)
End Sub
And it is working but how can I separate the variables and paste it in single cells?
Thanks

Public Sub btcteste()
Dim xmlhttp As Object
'Dim xmlhttp As New MSXML2.ServerXMLHTTP60
Set xmlhttp = CreateObject("MSXML2.serverXMLHTTP")
Dim myurl As String
myurl = "https://api.blinktrade.com/api/v1/BRL/ticker?crypto_currency=BTC"
xmlhttp.Open "GET", myurl, False
xmlhttp.send
Dim data As Variant
data = xmlhttp.responseText
Debug.Print data
' example data
' {"high": 13400.0, "vol": 616.03500983, "buy": 12830.59, "last": 12899.78, "low": 11800.0, "pair": "BTCBRL", "sell": 12899.78, "vol_brl": 7808332.67293126}
' split at comma (,) , and then split at colon (:)
data = Split(data, ",") ' convert to array
ActiveWorkbook.Sheets("Sheet1").Range("b2:b4") = Application.Transpose(Array("buy", "sell", "vol"))
' buy, sell and vol
ActiveWorkbook.Sheets("Sheet1").Range("c2") = Split(data(2), ":")(1) ' buy
ActiveWorkbook.Sheets("Sheet1").Range("c3") = Split(data(6), ":")(1) ' sell
ActiveWorkbook.Sheets("Sheet1").Range("c4") = Split(data(1), ":")(1) ' vol
End Sub

Try this code.
Public Sub btcteste()
Dim xmlhttp As Object
'Dim xmlhttp As New MSXML2.ServerXMLHTTP60
Set xmlhttp = CreateObject("MSXML2.serverXMLHTTP")
Dim myurl As String
Dim strText As String
Dim vSplit As Variant, v As Variant
Dim vR() As Variant
Dim n As Integer
myurl = "https://api.blinktrade.com/api/v1/BRL/ticker?crypto_currency=BTC"
xmlhttp.Open "GET", myurl, False
xmlhttp.send
'MsgBox (xmlhttp.responseText)
strText = xmlhttp.responseText
strText = Replace(strText, "}", "")
strText = Replace(strText, "{", "")
strText = Replace(strText, Chr(34), "")
vSplit = Split(strText, ",")
For Each v In vSplit
n = n + 1
ReDim Preserve vR(1 To 2, 1 To n)
vR(1, n) = Trim(Split(v, ":")(0))
vR(2, n) = Trim(Split(v, ":")(1))
Next v
Range("a1").Resize(n, 2) = WorksheetFunction.Transpose(vR) '<~~ this is vertical
'Range("a1").Resize(2, n) = vR '<~~ this is horisontal
End Sub

Related

How to call data stored in a CSV/TEXT file format to range

Good day,
I am struggling to proceed further from this, so with some research, I managed to this point and now i am stuck.
I need assistance to load the data into EXCEL as a datatable.
Here is my code.
Sub MDM_API_CALL()
Dim hReq As Object
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Sheet1")
Dim strUrl As String
strUrl = "url to request bearer token"
Set hReq = CreateObject("MSXML2.ServerXMLHTTP.6.0")
With hReq
.Open "POST", strUrl, False
.Send
End With
Dim response As String
response = hReq.responseText
authKey = Mid(response, 11, Len(Mid(response, 11, Len(response) - 12)))
strUrl = "url that requests the data in CSV format"
Set hReq = CreateObject("MSXML2.XMLHTTP")
With hReq
.Open "GET", strUrl, False
.SetRequestHeader "Authorization", "Bearer " & authKey
.Send
End With
response = hReq.responseText
ws.Range("A1").Value = response
End Sub
After the code, the data is saved in cell A1 and my data is cropped due to the cell limit.
Thank you

my MSXML2 code not working after 24. loop

the code below doesn't save the data, usually after 24 loops. why might that be? thank you.
Public Sub XmlHttpTutorial()
For x = 1 To 50
Dim xmlhttp As New MSXML2.XMLHTTP60, myurl As String
myurl = "https://www.etsy.com/shop/SilverHandwriting/reviews?page=" & x
xmlhttp.Open "GET", myurl, False
xmlhttp.send
Sheets("sayfa1").Cells(x, "a") = xmlhttp.responseText
Next x
End Sub

VBA: Subscript out of range or Type Mismatch

Very new to VBA, and am really stuck. Below is my code, you'll see near the end my For loop for Des and DesArr. All I'm trying to do with that loop is pull a column of cells from the work sheet "SIC", which is Sheet2 in my Workbook, I either get the error "Subscript out of Range" or "Type Mismatch" and whenever I try and google/correct for one, the other error takes its place. If anyone can help me work through this I'd greatly appreciate it!
Public Sub getGoogleDescriptions(strSearch As String)
Dim URL As String, strResponse As String
Dim objHTTP As Object
Dim htmlDoc As HTMLDocument
Dim result As String
Dim i As Integer
Dim u As Integer
Dim resultArr As Variant
Dim Des As String
Dim DesArr(2 To 48) As Long
Set htmlDoc = CreateObject("htmlfile")
'Set htmlDoc = New HTMLDocument
Dim objResults As Object
Dim objResult As Object
strSearch = Replace(strSearch, " ", "+")
URL = "https://www.google.com/search?q=" & strSearch
Set objHTTP = CreateObject("MSXML2.XMLHTTP")
With objHTTP
.Open "GET", URL, False
.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
.send
htmlDoc.body.innerHTML = .responseText
End With
Set objResults = htmlDoc.getElementsByClassName("st")
Debug.Print objResults(0).innerText
result = CStr(objResults(0).innerText)
resultArr = Split(result, " ", -1, 0)
For i = LBound(resultArr) To UBound(resultArr) 'Define i to be the length of the List'
Debug.Print i, resultArr(i) 'Prints the corresponding index value and array element'
Next i 'repeat
Set htmlDoc = Nothing
Set objResults = Nothing
Set objHTTP = Nothing
Set wk = ActiveWorkbook
For u = 2 To 48
Des = Sheets("SIC").Range("C" & u).Value
DesArr(u) = Des
Next u
Debug.Print DesArr(2)
End Sub
You're getting type mismatch because it's expecting DesArr to be a long data type which is a number between -2,147,483,648 to 2,147,483,647.
In it's use within the subroutine, it's used as a variant. So 2 corrections - change it to a variant as shown below
Then just adjust your 2 to 48 to within your statement... in this case it's a simple offset of 2, so just use (u - 2) and your Variant length is 47 starting at 0 instead of 1.
Public Sub getGoogleDescriptions(strSearch As String)
Dim URL As String, strResponse As String
Dim objHTTP As Object
Dim htmlDoc As HTMLDocument
Dim result As String
Dim i As Integer
Dim u As Integer
Dim resultArr As Variant
Dim Des As String
Dim DesArr(0) : ReDim DesArr(46)
Set htmlDoc = CreateObject("htmlfile")
'Set htmlDoc = New HTMLDocument
Dim objResults As Object
Dim objResult As Object
strSearch = Replace(strSearch, " ", "+")
URL = "https://www.google.com/search?q=" & strSearch
Set objHTTP = CreateObject("MSXML2.XMLHTTP")
With objHTTP
.Open "GET", URL, False
.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
.send
htmlDoc.body.innerHTML = .responseText
End With
Set objResults = htmlDoc.getElementsByClassName("st")
Debug.Print objResults(0).innerText
result = CStr(objResults(0).innerText)
resultArr = Split(result, " ", -1, 0)
For i = LBound(resultArr) To UBound(resultArr) 'Define i to be the length of the List'
Debug.Print i, resultArr(i) 'Prints the corresponding index value and array element'
Next i 'repeat
Set htmlDoc = Nothing
Set objResults = Nothing
Set objHTTP = Nothing
Set wk = ActiveWorkbook
For u = 2 To 48
Des = Sheets("SIC").Range("C" & u).Value
DesArr(u - 2) = Des
Next u
Debug.Print DesArr(0)
End Sub

VBA HTML Scraping - '.innertext' from complex table

All,
I've created the following Module to scrape a single value (1m % change in London house prices) from the below address:
https://www.hometrack.com/uk/insight/uk-cities-house-price-index/
The specific value is nested within the following code:
The below VBA code is my attempt at scraping. I, perhaps wrongly, feel that I am very close to capturing the value - but the code will not work.
Does anyone know where I am going wrong here? It doesn't show an error message but also doesn't output any values.
Sub HousePriceData()
Dim wb As Workbook
Dim ws As Worksheet
Dim TxtRng As Range
Dim ie As Object
Dim V As Variant
Dim myValue As Variant
Set ie = CreateObject("INTERNETEXPLORER.APPLICATION")
ie.NAVIGATE "https://www.hometrack.com/uk/insight/uk-cities-house-price-index/"
ie.Visible = False
While ie.ReadyState <> 4
DoEvents
Wend
Set wb = ActiveWorkbook
Set ws = wb.Sheets("Input")
Set TxtRng = ws.Range("C15")
Set myValue = ie.document.getElementById("cities-index-table").getElementsByTagName("tr")(7).g‌​etElementsByTagName("td")(5)
TxtRng = myValue.innerText
End Sub
Try to use XHR and primitive parsing instead of awkward IE:
Sub Test()
Dim strUrl As String
Dim strTmp As String
Dim arrTmp As Variant
strUrl = "https://www.hometrack.com/uk/insight/uk-cities-house-price-index/"
With CreateObject("MSXML2.XMLHttp")
.Open "GET", strUrl, False
.Send ""
strTmp = .ResponseText
End With
arrTmp = Split(strTmp, ">London</a></td>", 2)
strTmp = arrTmp(1)
arrTmp = Split(strTmp, "<td>", 7)
strTmp = arrTmp(6)
arrTmp = Split(strTmp, "</td>", 2)
strTmp = arrTmp(0)
ThisWorkbook.Sheets("Input").Range("C15").Value = strTmp
End Sub
try use this
Dim Engmt As String
Engmt = "ERRORHERE"
On Error Resume Next
Engmt = Trim(ie.document.getElementById("cities-index- table").getElementsByTagName("tr")(12).g‌​etElementsByTagName("td")(4).innerText)
On Error GoTo 0
If Engmt = "ERRORHERE" Then
TxtRng.Value = "ERROR"
Else
TxtRng.Value = Engmt
End If

convert ADODB binary stream to string vba

I have the following problem:
I have a CSV file which is stored on a server but it has 3 characters as delimiters: "[|]". I would like to load the data from the URL and fill the data in the columns of my Excel page using the [|] as delimiter. Until now I found code to load the file from a website using an ADODB recordset but I cannot get any further:
myURL = "http://www.example.com/file.csv"
Set WinHttpReq = CreateObject("Microsoft.XMLHTTP")
WinHttpReq.Open "GET", myURL, False, "username", "password"
WinHttpReq.send
myURL = WinHttpReq.responseBody
If WinHttpReq.Status = 200 Then
Set oStream = CreateObject("ADODB.Stream")
oStream.Open
oStream.Type = 1 'binary type
oStream.Write WinHttpReq.responseBody
oStream.SaveToFile "E:\file.csv", 2 ' 1 = no overwrite, 2 = overwrite
oStream.Close
End If
This works fine to save a file directly. But I do not want to save it to a file, I want to enter the data in the proper cells. Is there any way to do this? I would prefer not tu use Internet Explorer objects
Tested OK with a regular csv file:
Sub Tester()
Dim myURL As String, txt As String, arrLines, arrVals
Dim l As Long, v As Long, WinHttpReq As Object
Dim rngStart As Range
myURL = "http://www.mywebsite.com/file.csv"
Set WinHttpReq = CreateObject("Microsoft.XMLHTTP")
WinHttpReq.Open "GET", myURL, False, "username", "password"
WinHttpReq.send
txt = WinHttpReq.responseText
'might need to adjust vbLf >> vbCrLf or vbCr
' depending on the file origin (Win/Unix/Mac)
arrLines = Split(txt, vbLf)
Set rngStart = ActiveSheet.Range("A1")
For l = 0 To UBound(arrLines)
arrVals = Split(arrLines(l), "[|]")
For v = 0 To UBound(arrVals)
rngStart.Offset(l, v).Value = arrVals(v)
Next v
Next l
End Sub
you can use the ADO.Stream also with local files with the LoadFromFile method and store the value into a local variable. I have here an example where this is used to read a file that uses UTF-8 code page.
Dim adoStream As ADODB.Stream
Dim strText As String
Set adoStream = New ADODB.Stream
adoStream.Charset = "UTF-8"
adoStream.Open
adoStream.LoadFromFile "C:\Temp\Datei.txt"
strText = adoStream.ReadText
adoStream.Close
Set adoStream = Nothing
If the file isn't a UTF-8 one then simply delete the row with the Charset.
After that you ahve the entire file content in the variable strText. You can then use the split() function to cut by using the delimiter.
here is how I get page content:
Dim oRequest As Object
Set oRequest = CreateObject("WinHttp.WinHttpRequest.5.1")
oRequest.Open "GET", "http://www.cboden.de"
oRequest.Send
MsgBox oRequest.ResponseText
this should also work for CSV