Accessing SurveyMonkey API from VBA - excel

I am tying to set-up a Excel VBA project to readout individual survey responses into a form in Excel for some calculations and then PDF reporting.
However I have great difficulty to deploy the .NET library (SurveyMonkeyApi) to be available for reference in VBA.
I have set up a VisualStudio project to test that way , and I can install it for that specific VS project (through NuGet PM). But the library is not made available for Excel on that machine.
I have downloaded (on another machine) the libraries through standalone NuGet and they download OK but then I am at loss on how to register for Excel VBA access. On top of it there is a dependency on NewtonsoftJson library too (which downloaded automatically on both occasions).
Good advice appreciated!

I just saw this now - is there a feature for StackOverflow to alert me when a comment is added or a question answered, so I know to look back?
Here is starting code:
Option Explicit
Public Const gACCESS_TOKEN As String = "xxxxxxxxxxxxxxxxxxxxxx"
Declare Function GetTickCount Lib "kernel32" () As Long
Declare Sub Sleep Lib "kernel32" (ByVal lngMilliSeconds As Long)
' for a JSON parser see https://code.google.com/p/vba-json/
Public Sub test()
Dim vRequestBody As Variant, sResponse As String, sSurveyID As String
sSurveyID = "1234567890"
vRequestBody = "{""survey_id"":" & """" & sSurveyID & """" _
& ", ""fields"":[""collector_id"", ""url"", ""open"", ""type"", ""name"", ""date_created"", ""date_modified""]" _
& "}"
sResponse = SMAPIRequest("get_collector_list", vRequestBody)
End Sub
Function SMAPIRequest(sRequest As String, vRequestBody As Variant) As String
Const SM_API_URI As String = "https://api.surveymonkey.net/v2/surveys/"
Const SM_API_KEY As String = "yyyyyyyyyyyyyyyyyyyyyyyy"
Dim bDone As Boolean, sMsg As String, sUrl As String, oHttp As Object ' object MSXML2.XMLHTTP
Static lsTickCount As Long
If Len(gACCESS_TOKEN) = 0 Then
Err.Raise 9999, "No Access token"
End If
On Error GoTo OnError
sUrl = SM_API_URI & URLEncode(sRequest) & "?api_key=" & SM_API_KEY
'Debug.Print Now() & " " & sUrl
Application.StatusBar = Now() & " " & sRequest & " " & Left$(vRequestBody, 127)
Set oHttp = CreateObject("MSXML2.XMLHTTP") ' or "MSXML2.ServerXMLHTTP"
Do While Not bDone ' 4.33 offer retry
If GetTickCount() - lsTickCount < 1000 Then ' if less than 1 sec since last call, throttle to avoid sResponse = "<h1>Developer Over Qps</h1>"
Sleep 1000 ' wait 1 second so we don't exceed limit of 2 qps (queries per second)
End If
lsTickCount = GetTickCount()
'Status Retrieves the HTTP status code of the request.
'statusText Retrieves the friendly HTTP status of the request.
'Note The timeout property has a default value of 0.
'If the time-out period expires, the responseText property will be null.
'You should set a time-out value that is slightly longer than the expected response time of the request.
'The timeout property may be set only in the time interval between a call to the open method and the first call to the send method.
RetryPost: ' need to do all these to retry, can't just retry .Send apparently
oHttp.Open "POST", sUrl, False ' False=not async
oHttp.setRequestHeader "Authorization", "bearer " & gACCESS_TOKEN
oHttp.setRequestHeader "Content-Type", "application/json"
oHttp.send CVar(vRequestBody) ' request body needs brackets EVEN around Variant type
'-2146697211 The system cannot locate the resource specified. => no Internet connection
'-2147024809 The parameter is incorrect.
'String would return {"status": 3, "errmsg": "No oJson object could be decoded: line 1 column 0 (char 0)"} ??
'A Workaround would be to use parentheses oHttp.send (str)
'"GET" err -2147024891 Access is denied.
'"POST" Unspecified error = needs URLEncode body? it works with it but
SMAPIRequest = oHttp.ResponseText
'Debug.Print Now() & " " & Len(SMAPIRequest) & " bytes returned"
sMsg = Len(SMAPIRequest) & " bytes returned in " & (GetTickCount() - lsTickCount) / 1000 & " seconds: " & sRequest & " " & Left$(vRequestBody, 127)
If Len(SMAPIRequest) = 0 Then
bDone = MsgBox("No data returned - do you wish to retry?" _
& vbLf & sMsg, vbYesNo, "Retry?") = vbNo
Else
bDone = True ' got reply.
End If
Loop ' Until bdone
Set oHttp = Nothing
GoTo ExitProc
OnError: ' Pass True to ask the user what to do, False to raise to caller
Select Case MsgBox(Err.Description, vbYesNoCancel, "SMAPIRequest")
Case vbYes
Resume RetryPost
Case vbRetry
Resume RetryPost
Case vbNo, vbIgnore
Resume Next
Case vbAbort
End
Case Else
Resume ExitProc ' vbCancel
End Select
ExitProc:
End Function
Public Function URLEncode(StringVal As String, Optional SpaceAsPlus As Boolean = False) As String
Dim StringLen As Long
StringLen = Len(StringVal)
If StringLen > 0 Then
ReDim result(StringLen) As String
Dim i As Long, CharCode As Integer
Dim Char As String, Space As String
If SpaceAsPlus Then Space = "+" Else Space = "%20"
For i = 1 To StringLen
Char = Mid$(StringVal, i, 1)
CharCode = Asc(Char)
Select Case CharCode
Case 97 To 122, 65 To 90, 48 To 57, 45, 46, 95, 126
result(i) = Char
Case 32
result(i) = Space
Case 0 To 15
result(i) = "%0" & Hex(CharCode)
Case Else
result(i) = "%" & Hex(CharCode)
End Select
Next i
URLEncode = Join(result, "")
End If
End Function
EDIT 23-APRIL add more code.
the Me. comes from code in a Userform.
Set jLib = New JSONLib
vRequestBody = "{"
If Me.txtDaysCreated > "" Then
vRequestBody = vRequestBody & JKeyValue("start_date", Format$(Now() - CDbl(Me.txtDaysCreated), "yyyy-mm-dd")) & ","
End If
If Me.txtTitleContains > "" Then
' title contains "text", case insensitive
vRequestBody = vRequestBody & JKeyValue("title", Me.txtTitleContains) & ","
End If
vRequestBody = vRequestBody _
& JKeyValue("fields", Array("title", "date_created", "date_modified", "num_responses", _
"language_id", "question_count", "preview_url", "analysis_url")) & "}"
'returns in this order: 0=date_modified 1=title 2=num_responses 3=date_created 4=survey_id
' and in date_created descending
sResponse = GetSMAPIResponse("get_survey_list", vRequestBody)
------------------------------------------
Function JKeyValue(sKey As String, vValues As Variant) As String
Dim jLib As New JSONLib
JKeyValue = jLib.toString(sKey) & ":" & jLib.toString(vValues)
Set jLib = Nothing
End Function
Edit 25-April overview of VBA code to get the data
This is covered in the SM documentation, but I'll sketch how that looks in VBA.
the response to get_survey_details gives you all the survey setup data. Use
Set oJson = jLib.parse(Replace(sResponse, "\r\n", " "))
to get a json object.
Set dictSurvey = oJson("data")
gives you the dictionary so you can get data like dictSurvey("num_responses"). I take it you know how to index into dictionary objects to get field values.
Set collPages = dictSurvey("pages")
gives you a collection of Pages. The undocumented field "position" gives you the order of pages in the survey UI.
For lPage = 1 To collPages.Count
Set dictPage = collPages(lPage)
Set collPageQuestions = dictPage("questions") ' gets you the Qs on this page
For lPageQuestion = 1 To collPageQuestions.Count
Set dictQuestion = collPageQuestions(lPageQuestion) ' gets you one Q
Set collAnswers = dictQuestion("answers") ' gets the QuestionOptions for this Q
For lAnswer = 1 To collAnswers.Count
Set dictAnswer = collAnswers(lAnswer) ' gets you one Question Option
etc etc
Then given the number of responses from above, loop through the respondents 100 at a time - again see the SM doc for details of how to specify start and end dates to do incremental downloads over time.
create a json object from the response to "get_respondent_list"
Collect the fields for each respondent and accumulate a list of at most 100 respondent IDs.
Then "get_responses" for that list.
Set collResponsesData = oJson("data")
For lResponse = 1 To collResponsesData.Count
If not IsNull(collResponsesData(lResponse)) then
... get fields...
Set collQuestionsAnswered = collResponsesData(lResponse)("questions")
For lQuestion = 1 To collQuestionsAnswered.Count
Set dictQuestion = collQuestionsAnswered(lQuestion)
nQuestion_ID = CDbl(dictQuestion("question_id"))
Set collAnswers = dictQuestion("answers") ' this is a collection of dictionaries
For lAnswer = 1 To collAnswers.Count
On Error Resume Next ' only some of these may be present
nRow = 0: nRow = CDbl(collAnswers(lAnswer)("row"))
nCol = 0: nCol = CDbl(collAnswers(lAnswer)("col"))
nCol_choice = 0: nCol_choice = CDbl(collAnswers(lAnswer)("col_choice"))
sText = "": sText = collAnswers(lAnswer)("text")
nValue = 0: nValue = Val(sText)
On Error GoTo 0
and save all those values in a recordset or sheet or whatever
Hope that helps.

I access the SM API in straight VBA.
Just CreateObject("MSXML2.XMLHTTP") then issue calls and use the SimpleJsON JSONLib to parse it.
If I wanted to access VB.Net code, I'd package it with ExcelDNA to create a XLL and that gives a straight Excel addin.

I would think you would need to add it into the References for your Excel project.
From the Ribbon, select, Tools, then References, then scroll through the list looking for something about SurveyMonkey API.

So encouraged by #sysmod I have tried to do something in VBA directly. I have left out the JSON for now as I am already in trouble. The below is giving me "Developer Inactive" as a result, though I have another project in VB.NET where the same key and token works fine.
Public Sub GetSMList()
Dim apiKey As String
Dim Token As String
Dim sm As Object
apiKey = "myKey"
Token = "myToken"
Set sm = CreateObject("MSXML2.XMLHTTP.6.0")
With sm
.Open "POST", "https://api.surveymonkey.net/v2/surveys/get_survey_list", False
.setRequestHeader "Authorization", "Bearer " & Token
.setRequestHeader "Content-Type", "application/json"
.send "api_key=" & apiKey
result = .responseText
End With
End Sub

Related

Using Excel VBA to load a website that is incompatible with IE11

In Excel VBA to load a website and get it into a sheet I have been using the following:
Dim IE As Object
Set IE = CreateObject("InternetExplorer.Application")
IE .navigate "https://www.wsj.com/market-data/bonds/treasuries"
And then I can copy and paste it into my Excel sheet.
But this website no longer works with IE11, and Excel VBA insists on using IE11 even though it is about to be deprecated.
Is there another way? I have also looked at:
Selenium: but it seems to be pretty much obsolete for VBA (not updated since 2016) and I couldn’t get it to work with Edge or Firefox in VBA anyway.
AutoIt: I got it to write the website’s HTML code to a TXT file (oHTTP = ObjCreate("winhttp.winhttprequest.5.1") ; $oHTTP.Open("GET", $URL1, False) ; $oHTTP.Send(); $oReceived = $oHTTP.ResponseText; FileWrite($file, $oReceived)) but the txt file contents are far from convenient as there is endless HTML stuff in it. It’ll take a fair amount of VBA code to sort through the mess, which probably means it won’t be reliable going forward. Also given the size of my workbook which is very slow, it will take literally several minutes to copy the website data into a sheet element by element.
Surely there must be an easy way to load the site, or just the table within the site, into an Excel sheet? This must be a well trodden path, but after much googling I can’t find an easy solution that actually works.
I have a 5-10 web pages being loaded into this workbook, and it seems to be a full time job keeping the whole thing working!! Any thoughts/help very much appreciated!!!
Similar idea to Christopher's answer in using regex. I am grabbing the instruments data (JS array), splitting the component dictionaries out (minus the end }), and then use regex, based on headers, to grab the appropriate values.
I use a dictionary to handle input/output headers, and set a couple of request headers to help to signal browser based request and to mitigate for being served cached results.
Ideally, one would use an html parser and grab the script tag, then use a json parser on the JavaScript object within the script tag.
If you want the data from the other tabbed results, I can add that in by explicitly setting re.Global = True, then looping the returned matches. Depends whether you want those and how you want them to appear in the sheet(s).
I currently write results out to a sheet called Treasury Notes & Bonds.
Option Explicit
Public Sub GetTradeData()
Dim s As String, http As MSXML2.XMLHTTP60 'required reference Microsoft XML v6,
Set http = New MSXML2.XMLHTTP60
With http
.Open "GET", "https://www.wsj.com/market-data/bonds/treasuries", False
.setRequestHeader "User-Agent", "Mozilla/5.0"
.setRequestHeader "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT"
.send
s = .responseText
End With
Dim re As VBScript_RegExp_55.RegExp 'required reference Microsoft VBScript Regular Expressions
Set re = New VBScript_RegExp_55.RegExp
re.Pattern = "instruments"":\[(.*?)\]"
s = re.Execute(s)(0).SubMatches(0)
Dim headers() As Variant, r As Long, c As Long, mappingDict As Scripting.Dictionary 'required reference Microsoft Scripting Runtime
Set mappingDict = New Scripting.Dictionary
mappingDict.Add "maturityDate", "MATURITY"
mappingDict.Add "coupon", "COUPON"
mappingDict.Add "bid", "BID"
mappingDict.Add "ask", "ASKED"
mappingDict.Add "change", "CHG"
mappingDict.Add "askYield", "ASKED YIELD"
headers = mappingDict.keys
Dim results() As String, output() As Variant, key As Variant
results = Split(s, "}")
ReDim output(1 To UBound(results), 1 To UBound(headers) + 1)
For r = LBound(results) To UBound(results) - 1
c = 1
For Each key In mappingDict.keys
re.Pattern = "" & key & """:""(.*?)"""
output(r + 1, c) = re.Execute(results(r))(0).SubMatches(0)
c = c + 1
Next
Next
re.Pattern = "timestamp"":""(.*?)"""
re.Global = True
With ThisWorkbook.Worksheets("Treasury Notes & Bonds")
.UsedRange.ClearContents
Dim matches As VBScript_RegExp_55.MatchCollection
Set matches = re.Execute(http.responseText)
.Cells(1, 1) = matches(matches.Count - 1).SubMatches(0)
.Cells(2, 1).Resize(1, UBound(headers) + 1) = headers
.Cells(3, 1).Resize(UBound(output, 1), UBound(output, 2)) = output
End With
End Sub
The following code (not using web drivers) works but isn't an easy solution. I was able to find the information stored within the body, which was isolated by using REGEX and then stored into a JSON file for parsing.
Dim XMLPage As New MSXML2.XMLHTTP60
Dim HTMLDoc As New MSHTML.HTMLDocument
Dim strPattern As String: strPattern = "window.__STATE__ = ({.+}}}});"
Dim JSON As Object
Dim Key As Variant
Dim key1, key2 As String
XMLPage.Open "GET", "https://www.wsj.com/market-data/bonds/treasuries", False
XMLPage.send
Set JSON = JsonConverter.ParseJson(REGEX(XMLPage.responseText, strPattern, "$1"))
' Notes and Bonds
key1 = "mdc_treasury_{" & """" & "treasury" & """" & ":" & """" & "NOTES_AND_BONDS" & """" & "}"
For Each Key In JSON("data")(key1)("data")("data")("instruments")
Debug.Print Key("maturityDate")
Debug.Print Key("ask")
Debug.Print Key("askYield")
Debug.Print Key("bid")
Debug.Print Key("change")
Next Key
' Bills
key2 = "mdc_treasury_{" & """" & "treasury" & """" & ":" & """" & "BILLS" & """" & "}"
For Each Key In JSON("data")(key2)("data")("data")("instruments")
Debug.Print Key("maturityDate")
Debug.Print Key("ask")
Debug.Print Key("askYield")
Debug.Print Key("bid")
Debug.Print Key("change")
Next Key
The following function will need to be copied into a module:
Function REGEX(strInput As String, matchPattern As String, Optional ByVal outputPattern As String = "$0") As Variant
Dim inputRegexObj As New VBScript_RegExp_55.RegExp, outputRegexObj As New VBScript_RegExp_55.RegExp, outReplaceRegexObj As New VBScript_RegExp_55.RegExp
Dim inputMatches As Object, replaceMatches As Object, replaceMatch As Object
Dim replaceNumber As Integer
With inputRegexObj
.Global = True
.MultiLine = True
.IgnoreCase = False
.Pattern = matchPattern
End With
With outputRegexObj
.Global = True
.MultiLine = True
.IgnoreCase = False
.Pattern = "\$(\d+)"
End With
With outReplaceRegexObj
.Global = True
.MultiLine = True
.IgnoreCase = False
End With
Set inputMatches = inputRegexObj.Execute(strInput)
If inputMatches.Count = 0 Then
REGEX = False
Else
Set replaceMatches = outputRegexObj.Execute(outputPattern)
For Each replaceMatch In replaceMatches
replaceNumber = replaceMatch.SubMatches(0)
outReplaceRegexObj.Pattern = "\$" & replaceNumber
If replaceNumber = 0 Then
outputPattern = outReplaceRegexObj.Replace(outputPattern, inputMatches(0).value)
Else
If replaceNumber > inputMatches(0).SubMatches.Count Then
'regex = "A to high $ tag found. Largest allowed is $" & inputMatches(0).SubMatches.Count & "."
REGEX = CVErr(xlErrValue)
Exit Function
Else
outputPattern = outReplaceRegexObj.Replace(outputPattern, inputMatches(0).SubMatches(replaceNumber - 1))
End If
End If
Next
REGEX = outputPattern
End If
End Function
The following resources will help:
How to use Regular Expressions (Regex) in Microsoft Excel both in-cell and loops
https://github.com/VBA-tools/VBA-JSON
You will need to install the JSON converter and reference Regular Expression in the library. The REGEX function was found elsewhere on stack overflow so someone else deserves the credit for it.

Origins Destinations Excel VBA API (Google Maps)

I am trying to find the distance and travel time between multiple origins and destinations. For some reason, my code does not work at all. There are no errors, i just have nothing as output. See the attached Image for Excel worksheet.
Sub Origins_Destinations()
Dim a, b, i, Str As String
Dim lineS As Variant
On Error Resume Next
'Application.ScreenUpdating = False
With CreateObject("WinHttp.WinHttpRequest")
Dim iRow As Long: iRow = ThisWorkbook.Worksheets(1).Range("g65000").End(xlUp).Row
For j = 4 To iRow
b = ThisWorkbook.Worksheets(1).Range("b4" & j)
a = ThisWorkbook.Worksheets(1).Range("a4" & j)
.Open "GET", "https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=" & a & " &destinations= " & b & " &key=MY_KEY", False
.Send
lineS = Split(.ResponseText, vbLf)
For k = 25 To UBound(lineS)
If Trim(lineS(k)) = """distance"" : {" Then
Exit For
End If
Next k
ThisWorkbook.Worksheets(1).Range("c" & j) = lineS(k + 1)
ThisWorkbook.Worksheets(1).Range("d" & j) = lineS(k + 5)
Application.Wait (Now + TimeValue("0:00:01"))
Next j
End With
Application.ScreenUpdating = True
End Sub
enter image description here
Any suggestions ?????
As far as I understand, the code below is what you're looking for to get you started. Enter your Google Maps API Key in the Constant at the top, and then run sub TestRun.
It will replace disallowed characters in the address you provided, then loads the JSON results from Google Matrix into a string, and then, since we're only looking for 1 or 2 values, it will use a messy cheater-method to location the values, that I can't guarantee will always work:
It finds the first occurrence of the word "distance", and then the first occurrence of the word "value" after that, move 3 more characters to the right, and then take whatever is between there and the next " " blank space, and converts it to a value, hopefully the distance in meters.
Then it repeats (from beginning of file) to find "duration" in seconds, the same method. Note that the distance and duration are being returned to variables "byref".
As I said, it's very convoluted, but you get what you pay for. (Normally I wouldn't share code this "yucky", but you're in my neighborhood, so, Go Canada!)
Option Explicit
'3333 University Way,Kelowna,BC,V1V 1V7
'1555 Banks Rd, Kelowna, BC, V1X 7Y8
'1938 Pandosy Street, Kelowna, BC, V1Y 1R7
'2280 Baron Rd, Kelowna, BC, V1X 7W3
Const key = "YOUR-API-KEY-HERE"
Sub testRun()
Dim orig As String, dest As String, distance_Meters As Long, duration_Sec As Long
orig = EncodeEscapeString("3333 University Way,Kelowna,BC,V1V 1V7")
dest = EncodeEscapeString("1555 Banks Rd, Kelowna, BC, V1X 7Y8")
Call getGoogleDistanceMatrix(orig, dest, distance_Meters, duration_Sec)
Debug.Print distance_Meters & "m"
Debug.Print duration_Sec & "sec"
End Sub
Sub getGoogleDistanceMatrix(ByVal orig As String, ByVal dest As String, ByRef distance_Meters As Long, ByRef duration_Sec As Long)
Const distanceTag1 = """distance"""
Const distanceTag2 = """value"""
Const durationTag1 = """duration"""
Const durationTag2 = """value"""
Dim jSON As String, pStart As Long, pEnd As Long
jSON = Get_URL_text("https://maps.googleapis.com/maps/api/distancematrix/json?units=metric&origins=" & orig & "&destinations=" & dest & "&key=" & key)
pStart = InStr(jSON, distanceTag1) + Len(distanceTag1)
pStart = InStr(pStart, jSON, distanceTag2) + Len(distanceTag2) + 3
pEnd = InStr(pStart, jSON, " ")
distance_Meters = Val(Trim(Mid(jSON, pStart, pEnd - pStart)))
pStart = InStr(jSON, durationTag1) + Len(durationTag1)
pStart = InStr(pStart, jSON, durationTag2) + Len(durationTag2) + 3
pEnd = InStr(pStart, jSON, " ")
duration_Sec = Val(Trim(Mid(jSON, pStart, pEnd - pStart)))
End Sub
Function Get_URL_text(url As String) As String
Dim XMLHTTP As Object
Set XMLHTTP = CreateObject("MSXML2.serverXMLHTTP")
XMLHTTP.Open "GET", url, False
XMLHTTP.send
Get_URL_text = XMLHTTP.responseText
Set XMLHTTP = Nothing
End Function
Function EncodeEscapeString(str_In As String) As String
Dim s As String
s = str_In
s = Replace(s, "%", "%25")
s = Replace(s, " ", "%20")
s = Replace(s, Chr(34), "%22")
s = Replace(s, "<", "%3C")
s = Replace(s, ">", "%3E")
s = Replace(s, "#", "%23")
s = Replace(s, "|", "%7C")
EncodeEscapeString = s
End Function
This same "cheater method" can be used to to scrape bits of data from any URL (JSON, HTML, XML, CSV, etc) that has a consistent text output.
You may need to add a Tools -> Reference to support XMLHTTP.
Good luck with that! (and don't forget to "accept" this answer if it's at all useful, I already put more time into this than I intended!)

Using IEX API for real-time stock info (Yahoo Finance replacement)?

Just like the title says, I'm looking for a replacement source for stock info now that Yahoo has disabled the API many people have been using. The new source I've been looking at is found here: https://iextrading.com/developer/
My question is how to actually get the data in to Excel...I was thinking through VBA since that is what I had used to get the data from Yahoo. However, I think what I would like to do is well beyond my current abilities...I also tried using Excel's WEBSERVICE() function with the following URL to simply look at a price: https://api.iextrading.com/1.0/stock/aapl/price but that didn't work. From my understanding, IEX has made a plethora of data available to us for free, I just don't know how to access it. My reasoning for VBA is so that I am able to use an input list from a workbook for tickers, and would be able to put this data access in many workbooks. Any help is much appreciated. Additionally, any sort of direction as to where I can look to begin learning this on my own would be similarly welcome. Thanks.
Update: Code mentioned in my comment
Function StockPrice(ticker As String, item As String) As Double
Dim strURL As String, strCSV As Double, itemFound As Integer, tag As String
itemFound = 0
If item = "lastprice" Then
tag = "price"
itemFound = 1
ElseIf item = "pe" Then
tag = "peRatio"
itemFound = 1
End If
If itemFound = 1 Then
strURL = "https://api.iextrading.com/1.0/stock/" & ticker & "/" & tag
Set XMLHTTP = CreateObject("MSXML2.XMLHTTP")
XMLHTTP.Open "GET", strURL, False
XMLHTTP.send
StockPrice = XMLHTTP.responseText
Set XMLHTTP = Nothing
Else
StockPrice = "Item Not Found"
End If
End Function
This maybe a bit simplistic, but it's a start:
Sub IEX()
Dim Price As Single
Price = Application.WebService("https://api.iextrading.com/1.0/stock/aapl/price")
End Sub
I think I've mostly solved the issue. Here is the code for anyone who is interested. This works as a direct replacement for those using Yahoo Finance's API.
Function StockPrice(ticker As String, item As String)
Dim strURL As String, strCSV As Double, itemFound As Integer, tag As String
itemFound = 0
If item = "lastprice" Then
tag = "latestPrice"
itemFound = 1
ElseIf item = "pe" Then
tag = "peRatio"
itemFound = 1
ElseIf item = "company" Then
tag = "companyName"
itemFound = 1
ElseIf item = "sector" Then
tag = "sector"
itemFound = 1
ElseIf item = "open" Then
tag = "open"
itemFound = 1
ElseIf item = "yclose" Then
tag = "previousClose"
itemFound = 1
ElseIf item = "change" Then
tag = "change"
itemFound = 1
ElseIf item = "%change" Then
tag = "changePercent"
itemFound = 1
ElseIf item = "marketcap" Then
tag = "marketCap"
itemFound = 1
ElseIf item = "52high" Then
tag = "week52High"
itemFound = 1
ElseIf item = "52low" Then
tag = "week52Low"
itemFound = 1
End If
If itemFound = 1 Then
strURL = "https://api.iextrading.com/1.0/stock/" & ticker & "/quote/" & tag
Set XMLHTTP = CreateObject("MSXML2.XMLHTTP")
XMLHTTP.Open "GET", strURL, False
XMLHTTP.send
StockPrice = XMLHTTP.responseText
Set XMLHTTP = Nothing
Else
StockPrice = "Item Not Found"
End If
End Function
IEX has much more functionality than I've built here. Just not experienced enough to build around it. Check those features here: https://iextrading.com/developer/docs/
With ticker symbol in one cell (cell E3 in this example), enter the following in another cell:
=WEBSERVICE("https://api.iextrading.com/1.0/stock/" & E3 & "/quote/delayedPrice")
Works in Excel for Office 365.
If you don't need backwards compatibility with Yahoo, and just want a simple price quote, this VBA function adds a quote capability to the list of Excel functions.
It's not polished, but should serve as a simple example of how to use the powerful IEX API. Use the VBA editor to put this in a module:
Public Function tickerPrice(ticker As String)
Dim htmlCmd As String
Dim curlCmd As String
Dim shellCmd As String
Dim sResult As String
htmlCmd = "https://api.iextrading.com/1.0/stock/" & ticker & "/quote/delayedPrice"
curlCmd = "curl \""" & htmlCmd & "\"""
shellCmd = "do shell script "" " & curlCmd & " "" "
sResult = MacScript(shellCmd)
tickerPrice = Val(sResult)
End Function
Be sure to enable Macros when opening the workbook, so this can function. (This was tested with Mac Excel 2011, with High Sierra, in 2017.

vb.net to pull data from Excel Data GridView

I have 78 excel columns and I have 5 datagridviews.
How do I make connection?
I understand what you want to achieve, but to get the maximum out of any answer, it would be better if you add some code or some further explanation.
For example how should anyone know which excel data should be displayed in DataGridView one, two etc...
Anyway, i would recommend that you divide the task into two steps:
ReadExcel and DisplayData. In my opinion reading data from excel file via OLEDB is a good way to start. Therefore i recommend reading the following article: http://www.codeproject.com/Tips/705470/Read-and-Write-Excel-Documents-Using-OLEDB
For displaying the data in a DataGridView you need to bind a dataset to it. Maybe you´ll find the following post helpful:
How to bind Dataset to DataGridView in windows application
Its both c# code, but i think getting things running for vb.net is an easy task.
Edit: I found some older vb.net of mine you can use. It´s not that good piece of code but it should get you started. It imports the whole data of an excel sheet. But please don´t just copy and run :)
Public Shared Function ImportExcelSheetData(ByVal ExcelFilePath As String, _
ByVal SourceExcelSheetName As String, _
ByRef pDestDataTable As DataTable, _
ByRef ErrMsg As String, _
Optional ByVal WithHeader As Boolean = False) As Integer
Dim ConnectionString As String = ""
Dim WithHeaderString As String = ""
Dim nOutputRow As Integer = 0
Dim oleExcelCommand As OleDbCommand
Dim oleExcelConnection As OleDbConnection
ImportExcelSheetData = -1 ' Error by default
If System.IO.File.Exists(ExcelFilePath) <> True Then
ErrMsg = "Error: File does not exist." + vbCrLf + "Filepath: " + ExcelFilePath
Exit Function
End If
If WithHeader = True Then
WithHeaderString = "Yes"
Else
WithHeaderString = "No"
End If
ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ExcelFilePath + ";Extended Properties=""Excel 12.0;HDR=" + WithHeaderString + ";IMEX=1"""
oleExcelConnection = New OleDbConnection(ConnectionString)
oleExcelConnection.Open()
If IsNothing(pDestDataTable) = True Then
pDestDataTable = New DataTable
End If
' if SourceExcelSheetName is not set, use first sheet!
If SourceExcelSheetName.Trim = "" Then
Dim tmpDataTable As DataTable = oleExcelConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
if IsNothing(tmpDataTable) OR tmpDataTable.Rows.Count < 1 Then
throw new Exception("Error: Could not determine the name of the first worksheet.")
End If
Dim firstSheetName As String = tmpDataTable.Rows(0)("TABLE_NAME").ToString()
If firstSheetName.Trim() <> "" then
SourceExcelSheetName = firstSheetName
End If
End If
If SourceExcelSheetName <> "" Then
Try
Dim oleAdapter As New OleDbDataAdapter()
oleExcelCommand = oleExcelConnection.CreateCommand()
If SourceExcelSheetName.EndsWith ("$") = True Then
oleExcelCommand.CommandText = "Select * From [" & SourceExcelSheetName & "]"
Else
oleExcelCommand.CommandText = "Select * From [" & SourceExcelSheetName & "$]"
End If
oleExcelCommand.CommandType = CommandType.Text
oleAdapter.SelectCommand = oleExcelCommand
oleAdapter.Fill(pDestDataTable)
oleExcelConnection.Close()
Catch ex As Exception
ErrMsg = Err.Description
Exit Function
End Try
End If
ImportExcelSheetData = 0 ' Ok
End Function

How to use appIE.Document.Body.innerHTML

So I'm trying to retrieve the latitude and longitude of a given postal code, and am trying to use VBA to place this into an excel worksheet. My code is as follows:
Private appIE As Object
Function GeoCode(sLocationData As String) As String
'//Dont want to open and close all day long - make once use many
If appIE Is Nothing Then
CreateIEApp
'// Creates a new IE App
'// if = nothing now then there was an error
If appIE Is Nothing Then
GeoCode = "Sorry could not launch IE"
Exit Function
Else
'// do nothing
End If
Else
'// do nothing
End If
'//clearing up input data
'sLocationData = Replace(sLocationData, ",", " ")
sLocationData = Replace(sLocationData, " ", "+")
sLocationData = Trim(sLocationData)
'//Build URL for Query
sLocationData = "http://maps.google.com/maps/geo?q=%20_" & sLocationData
'// go to the google web service and get the raw CSV data
'// CAUSES PROBLEM AS SPECIFIED BELOW
appIE.Navigate sLocationData
Do While appIE.Busy
Application.StatusBar = "Contacting Google Maps API..."
Loop
Application.StatusBar = False
On Error Resume Next
'// Parsing
GeoCode = appIE.Document.Body.innerHTML
GeoCode = Mid(GeoCode, InStr(GeoCode, ",") + 1, InStr(GeoCode, "/") - InStr(GeoCode, ",") - 2)
appIE = Nothing
End Function
The Google Maps API then returns a JSON formatted value, as per this link:
http://maps.google.com/maps/geo?q=%20_400012
I then attempt to retrieve this value using
appIE.Document.Body.innerHTML,
and parsing that value for the data I want. However, the moment the code hits appIE.Navigate sLocationData,
I'm prompted to save a file called "geo". When saved and opened as a .txt file, I get the exact same JSON formatted value, but I need the values within my worksheet itself.
Is there a way to do this?
Thanks in advance!
That link didn't work for me in Firefox - response 610. If I remove the space and the underscore, it works. I don't know why IE wants to download, probably some setting that tells it to always download JSON rather than render it. In any case, consider using MSXML's http request rather than automating IE.
Set a reference to Microsoft XML, v6.0 or similar (VBE - Tools - References).
Function GeoCode(sLocData As String) As String
Dim xHttp As MSXML2.XMLHTTP
Dim sResponse As String
Dim lStart As Long, lEnd As Long
Const sURL As String = "http://maps.google.com/maps/geo?q="
Const sCOOR As String = "coordinates"": " 'substring that we'll look for later
'send the http request
Set xHttp = New MSXML2.XMLHTTP
xHttp.Open "GET", sURL & sLocData
xHttp.send
'wait until it's done
Do
DoEvents
Loop Until xHttp.readyState = 4
'get the returned data
sResponse = xHttp.responseText
'find the starting and ending points of the substring
lStart = InStr(1, sResponse, sCOOR)
lEnd = InStr(lStart, sResponse, "]")
GeoCode = Mid$(sResponse, lStart + Len(sCOOR), lEnd - lStart - Len(sCOOR) + 1)
End Function
Sub Test()
Dim sTest As String
sTest = GeoCode("400012")
Debug.Assert sTest = "[ 103.9041520, 1.3222160, 0 ]"
End Sub

Resources