how to invoke api url in outlook userform - vba

I have created userform and try to input parameters and invoke the api url to “create incident”
api url:https://***.com/incident/create
to create an incident http post a json payload to the url above,example as below
{
“state”:“**”
“caller_id”:“**”
.
.
.
“urgency”=“**”
}
outlook userfrom has been created for inputting parameters just to match the json,so how could user invoke the api url in the userform to “create incident” in the userform ui?

Here is an example which shows how you can use web calls from VBA (not only from user forms):
Sub listPokemons()
Dim json As String
Dim jsonObject As Object, item As Object
Dim i As Long
Dim ws As Worksheet
Dim objHTTP As Object
'We selected our results sheet
Set ws = Worksheets("results")
'We create our request object and send
Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
URL = "https://pokeapi.co/api/v2/pokemon"
objHTTP.Open "GET", URL, False
objHTTP.Send
strResult = objHTTP.responseText
json = strResult
Set objectJson = JsonConverter.ParseJson(json)
'We create the header cells
ws.Cells(1, 1) = "name"
ws.Cells(1, 2) = "link"
'We loop the results property of the API response
i = 2 'We will start the counter on line 2
For Each pokemon InJsonObject("results")
ws.Cells(i, 1) = pokemon("name")
ws.Cells(i, 2) = pokemon("url")
i = i + 1
next
End Sub
It is possible to perform all types of requests - GET, POST, UPDATE.
Read more about that in the How to use Excel VBA to query REST JSON APIs article.

Related

VBA web page scroll

I am getting a problem to scroll document in a proper position, also getting a problem to capture a proper detail in excel here is my Code please Sir suggest me where I am getting wrong
here i try with following code still getting some error
Public Sub GData()
'On Error Resume Next
Dim html As HTMLDocument
Dim Re, Cr, cipherDict As Object
Dim sResponse, cipherKey, Str, SG As String
Dim myArr, RsltArr(14) As Variant
Set Re = CreateObject("vbscript.regexp")
Set Cr = CreateObject("MSXML2.XMLHTTP")
Set cipherDict = CreateObject("Scripting.Dictionary")
Set html = New HTMLDocument
URL = "https://www.google.com/maps/place/Silky+Beauty+Salon/#22.2932632,70.7723656,17z/data=!3m1!4b1!4m5!3m4!1s0x3959ca1278f4820b:0x44e998d30e14a58c!8m2!3d22.2932632!4d70.7745543"
With Cr
.Open "GET", URL, False
.setRequestHeader "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT"
.send
sResponse = StrConv(.responseBody, vbUnicode)
s = .responseText
End With
With html
.body.innerHTML = sResponse
title = .querySelector("section-hero-header-title-title").innerText
phone = .querySelector("[data-item-id^=phone] [jsan*=text]").innerText
webSite = .querySelector("[aria-label^=Website] [jsan*=text]").innerText
End With
datarw = ActiveSheet.Cells(ActiveSheet.Rows.Count, "A").End(xlUp).Row + 1
ActiveSheet.Cells(datarw, 1).Value = title
ActiveSheet.Cells(datarw, 5).Value = phone
ActiveSheet.Cells(datarw, 7).Value = webSite
ActiveSheet.Cells(datarw, 1).Select
ActiveSheet.Rows(datarw).WrapText = False
End Sub
Looks like you can use combinations of different combinators (^ starts with and * contains) to search for substrings in attributes on the page to get your target nodes. Using descendant combinators to specify the relationship between attributes being used for anchoring.
Test if matched node Is Not Nothing before attempting to access either an attribute value or .innerText
Dim phone as Object, webSite As Object, title As Object
Set title = ie.document.querySelector(".section-hero-header-title-title")
Set phone = ie.document.querySelector("[data-item-id^=phone] [jsan*=text]")
Set website = ie.document.querySelector("[aria-label^=Website] [jsan*=text]")
If Not phone Is Nothing Then
'clean phone.innerText as appropriate
End If
If Not website Is Nothing Then
'clean website.innerText as appropriate
End If
To get the appropriate protocol for the website address, if missing, you can use the cleaned website address you have in a regex to pull the protocol from earlier in the html where it sits in a script tag.
Read about
css selectors: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors
querySelector: querySelector and querySelectorAll vs getElementsByClassName and getElementById in JavaScript

How to get the authorization code value from the redirect URI in VBA using XMLHTTP60 object?

I am trying to get the authorization code from my VBA macro as given here,
https://learn.microsoft.com/en-us/onedrive/developer/rest-api/getting-started/graph-oauth?view=odsp-graph-online
While I know a web page URL will get the code appended, I am not sure how to get the code value from the redirect Uri in a VBA object in those while I have set the redirect uri for mobile and desktop applications as suggested - "https://login.microsoftonline.com/common/oauth2/nativeclient" for the registered client in azure.
Below is the code,
Dim WinHttpReq As XMLHTTP60
Set WinHttpReq = New XMLHTTP60
myURL="https://login.microsoftonline.com/<MyTenantID>/oauth2/v2.0/authorize?client_id={MyClientID}&response_type=code&redirect_uri={https://login.microsoftonline.com/common/oauth2/nativeclient}&response_mode=query&scope=https://graph.microsoft.com/.default"
WinHttpReq.Open "POST", myURL
WinHttpReq.send
Debug.Print WinHttpReq.responseText
'Debug.Print WinHttpReq.responseBody
The above code returns some HTML and javascript as the response but not the Authorization code value.
I am trying to follow this - msGraph API from msAccess VBA - Planner plans credentials issue - but it looks like the redirect uri is pointing to web page to get the auth code.
How can I get it in my VBA WinHttpReq object?
I tried this (which works if you pass a redirecting bit.ly URL to it) but for OAuth, since the status returns 200 and not 301, the OAuth flow doesn't seem to look like a redirect as far as the HTTP object is concerned:
With WinHttpReq
.Open "POST", myURL
.Option(6) = True ' 6=WinHttpRequestOption_EnableRedirects
.Send
Debug.Print .Option(1) ' 1=WinHttpRequestOption_URL
Debug.Print .GetResponseHeader("Location")
End With
But this does work:
Function GetAuthCodeIE(myURL As String) As String
Const READYSTATE_COMPLETE As Long = 4
Dim oIE As Object
Set oIE = CreateObject("InternetExplorer.Application")
oIE.Navigate myURL
' Wait for response
While oIE.Busy Or oIE.readyState <> READYSTATE_COMPLETE
DoEvents
Wend
Dim Response As String
Response = oIE.LocationURL
Dim aResponse() As String
aResponse = Split(Response, "?")
aResponse = Split(aResponse(1), "&")
GetAuthCodeIE = Replace(aResponse(0), "code=", "")
End Function

Half of the records are getting scraped out of 84

I've made a parser in VBA which is able to scrape the name from yellow page Canada. However, the issue is that the page contains 84 Names but my parser is scraping only 41 Names. How can I fix this? Any help would be my blessing. Thanks in advance. Here is the code:
http.Open "GET", "http://www.yellowpages.ca/search/si/1/Outdoor%20wedding/Edmonton", False
http.send
html.body.innerHTML = http.responseText
Set topics = html.getElementsByClassName("listing__name--link jsListingName")
For Each topic In topics
Cells(x, 1) = topic.innerText
x = x + 1
Next topic
Btw, I used the MSxml2.xmlhttp60 request.
If you look at the page's web requests, you'll notice it'll trigger another web request once the page has been scrolled past a certain point.
The format of the new requests is like this:
First 40 records: http://www.yellowpages.ca/search/si/1/Outdoor%20wedding/Edmonton
Next 40 records: http://www.yellowpages.ca/search/si/2/Outdoor%20wedding/Edmonton
Next 40 records: http://www.yellowpages.ca/search/si/3/Outdoor%20wedding/Edmonton
Basically for new data (in batches of 40 records) it increments part of the URL by 1.
Which is good news, we can just do a loop to return the results. Here's the code I came up with. For whatever reason, the getElementsByClassName selector wasn't working for me, so I worked around it in my code. If you can use that selector, use that instead of what I have below for that part.
Lastly, I added an explicit reference to Microsoft XML v6.0, so you should do the same to get this to function as it is.
Option Explicit
Public Sub SOTestScraper()
Dim topics As Object
Dim topic As Object
Dim webResp As Object
Dim i As Long
Dim j As Long
Dim mySheet As Worksheet: Set mySheet = ThisWorkbook.Sheets("Sheet1") ' Change this
Dim myArr() As Variant: ReDim myArr(10000) 'Probably overkill
For i = 1 To 20 ' unsure how many records you expect, I defaulted to 20 pages, or 800 results
Set webResp = getWebResponse(CStr(i)) ' return the web response
Set topics = webResp.getElementsByTagName("*") ' I couldn't find the className so I did this instead
If topics Is Nothing Then Exit For 'Exit the for loop if Status 200 wasn't received
For Each topic In topics
On Error Resume Next
'If getElementByClassName is working for you, use it
If topic.ClassName = "listing__name--link jsListingName" Then
myArr(j) = topic.InnerText
j = j + 1
End If
Next
Next
'add the data to Excel
ReDim Preserve myArr(j - 1)
mySheet.Range("A1:A" & j) = WorksheetFunction.Transpose(myArr)
End Sub
Function getWebResponse(ByVal pageNumber As String) As Object
Dim http As MSXML2.ServerXMLHTTP60: Set http = New MSXML2.ServerXMLHTTP60
Dim html As Object: Set html = CreateObject("htmlfile")
With http
.Open "GET", "http://www.yellowpages.ca/search/si/" & pageNumber & "/Outdoor%20wedding/Edmonton"
.send
.waitForResponse
html.body.innerHTML = .responseText
.waitForResponse
End With
If Not http.Status = 200 Then
Set getWebResponse = Nothing
Else
Set getWebResponse = html
End If
Set html = Nothing
Set http = Nothing
End Function

After using a UDF Excel Stops Working during save

I have set up a keyboard shortcut (ctrl+alt+c) That calculates the users selection pretty basic I grabbed off of here
Private Sub Workbook_Open()
Application.OnKey "^%c", "CalculateSelection"
End Sub
Sub CalculateSelection()
On Error GoTo NoSelection
If Not Selection Is Nothing Then
If TypeName(Application.Selection) = "Range" Then
Dim Rng As Range
Set Rng = Application.Selection
Rng.Calculate
End If
End If
Exit Sub
NoSelection:
MsgBox ("No Range Selected")
End Sub
This works perfectly fine on all other cell and i can save my work when its all completed.
If I use this function on a cell that calls an API the function works fine until you save, Microsoft stops working entirely and I have no idea why.
Does anyone know why this might be happening? would this be cause by some object not being destroyed or is my excel corrupt?
All the API function work fine I've had no errors with them until I used this sub on them.
This is the function that sends the data to the API. It has different functions that are called from the sheet to format the data to XML and check whether the data being passed is correct and fully calculated.
Private Function PostToApiXmlToXml(Data As String, Route As String)
'Initialise Document Object Model to hold the XML
'And the xmlHttp to handle Sending Data
Dim xmlhttp As MSXML2.ServerXMLHTTP60
Dim XMLDOM As MSXML2.DOMDocument60
Set xmlhttp = CreateObject("MSXML2.ServerXMLHTTP")
Set XMLDOM = New MSXML2.DOMDocument60
'Load entire Document before moving on
'Data is a string but must conatin opening and closing tags.
XMLDOM.async = False
XMLDOM.LoadXML (Data)
'Using the Http object
With xmlhttp
Call .setOption(2, SXH_SERVER_CERT_IGNORE_ALL_SERVER_ERRORS)
'Set up a POST to the Base Address + Route
.Open "POST", BaseAddress + Route, False
'Content-Type Header is requred to let the API Know What type of Data you are Sending
.setRequestHeader "Content-Type", "application/xml"
'Accept Header Lets the Api know we want to recieve JSON Data
.setRequestHeader "Accept", "application/json"
'Send the Dom as XML in the http object
.send (XMLDOM.Xml)
'Take in the Response as text
PostToApiXmlToXml = .responseText
End With
Set xmlhttp = Nothing
End Function
I can use the keyboard shortcut anywhere on the sheet and save with no problems. and i can use it on single cells with API calls and press ctrl + s and it saves fine. But if i select multiple and press ctrl + alt + c then save with ctrl + s it corrupts the save and restores to previous save doesn't let me open or view any of the problems with the corrupted version.

Send SMS via VoipBuster using VBA

I am total beginner, but I am trying to make a macro in VBA to send an SMS using VoipBuster platform when a condition is completed.
Is it possible? Is it easier to use the application installed on PC or web page (https://www.voipbuster.com/sms).
Please help!
For send sms from voipbuster you can send it by php vars...
"https://www.voipbuster.com/myaccount/sendsms.php?username=$USER&password=$PASS&from=$FROM&to=\"$TO\"&text=$SMS_TEXT"
So you need to access iexplore from vba like this , create you vars use, pass, text etcc and concat everythins like the URL before ..
to call iexplore from VBA you will find a lot of ways with google , here you got an example
Private Sub IE_Autiomation()
Dim i As Long
Dim IE As Object
Dim objElement As Object
Dim objCollection As Object
' Create InternetExplorer Object
Set IE = CreateObject("InternetExplorer.Application")
' You can uncoment Next line To see form results
IE.Visible = False
' Send the form data To URL As POST binary request
IE.Navigate "https://www.voipbuster.com/myaccount/sendsms.php?username=$USER&password=$PASS&from=$FROM&to=\"$TO\"&text=$SMS_TEXT"
Try below code. You can also test by putting the value in URL variable to your browser.
Sub SendSms()
Dim username As String
Dim password As String
Dim sendTo As String
Dim msg As String
username = "test" 'enter username here
password = "test" 'enter password here
sendTo = "9999999999"
msg = "Hello"
Dim URL As String
URL = "https://www.voipbuster.com/myaccount/sendsms.php?username=" & username & "&password=" & password & "&to=" & sendTo & "&text=" & msg
Dim xml As Object
Set xml = CreateObject("MSXML2.XMLHTTP")
xml.Open "GET", URL, False
xml.send
End Sub