Try catch block in Outlook Macro - vba

I had a piece of code to send data to a HTTP end point
Set xhr = CreateObject("MSXML2.XMLHTTP")
xhr.Open "POST", URL, False
xhr.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
Data = "volumeDate=" & URLEncode(VolumeDate) & "&" & "volume=" & URLEncode(Volume)
xhr.Send Data
I want to have a try catch block to handle if it didnt connect to the URL or if it returned something apart from a 200
How do I do it?

Error handling in VBA is based on the On Error statement. Take a look at the Error Handling In VBA for more information.
I'd suggest creating a COM add-in instead of VBA macros. You will be able to check the error code easily and handle exceptions gracefully. See Walkthrough: Creating Your First VSTO Add-In for Outlook to get started quickly.

Related

How to POST JSON data to an API using VBscript

I am currently working on a signup form and I want users to be pushed to my hubspot account upon sign up. The form is built in a .asp file format using HTML, CSS, and VBscript. I want the user to fill out all of the required fields and then send their responses to Hubspot using their Create Contact API endpoint.
The form itself is built out and working, now all I need to do is link up the API POST request. I am not familiar with VBscript or how one could go about sending JSON data to an API using VB. I started out by just trying to send dummy data that would be easily searchable figuring I can work on making the values dynamic later, but even this won't work. This is the code that I have written directly in the markup. Any help is appreciated!
<%
Dim objXmlHttpMain, URL, strJSONToSend
strJSONToSend = "{'properties': [{'property': 'email','value': 'testingapis#hubspot.com'},{'property': 'firstname','value': 'Adrian'},{'property': 'lastname','value': 'Mott'},{'property': 'website','value': 'http://hubspot.com'},{'property': 'company','value': 'HubSpot'},{'property': 'phone','value': '555-122-2323'},{'property': 'address',},{'property': 'city','value': 'Cambridge'},'property': 'state','value': 'MA'},{'property': 'zip','value': '02139'}]}"
URL="https://api.hubapi.com/contacts/v1/contact/?hapikey=df670ac6-cc2d-452d-a571-11d0374e515e"
Set objXmlHttpMain = CreateObject("Msxml2.ServerXMLHTTP")
On Error Resume Next
objXmlHttpMain.open "POST",URL, False
If Err Then
WScript.Echo Err.Description & " [0x" & Hex(Err.Number) & "]"
WScript.Quit 1
End If
On Error Goto 0
objXmlHttpMain.open "POST",URL, False
objXmlHttpMain.setRequestHeader "Accept", "application/json>"
objXmlHttpMain.setRequestHeader "Content-Type", "application/json"
objXmlHttpMain.send strJSONToSend
set objJSONDoc = nothing
set objResult = nothing
%>

Posting with an open event

Action: Trying to 'post' excel data to a webpage that the user sees/uses with a vba code event.
Issue: I can open a window with a get, or I can xmlhttp with a post and a get a response variable, but neither is what I need. I need to POST login information (a service account) from baked in vba code on a button to POST and open a browser.
The webpage is behind Spring Security and the service account credentials should not be known to the user, it's hidden in a protected workbook/vba. I need to post those over to the url.
--> How do I open AND post at the same time?
What I need is the excel equivalent of an HTML form post with a
target=_blank
attribute in vba. Is this possible?
I've tried both
ShellExecute
functions
and
xmlhttp
methods
but both only give me half of the package.
Any advice?
Adding to what #Florent B. has posted, check whether the cookie is set when calling the login page (which I assume) or really when posting the login data.
Dim xhttp As MSXML2.XMLHTTP ' make sure you reference to MSXML!
Dim strCookie As String
Set xHttp = New MSXML2.XMLHTTP
XMLHttp.Open "GET" TheURLOfYourLogInPage
If xHttp.Status = 200 Then
strCookie = xHttp.getResponseHeader("Set-Cookie")
End If
Check your web browser for what is sent to the server when login in, probably something like "username=" & YourUserName & "&password=" & YourPassword & "&cookie=" & strCookie Declare another string variable (I will call it strTicker) and fill it accordingly, then
xHttp.Open "POST", "URLOfYourLoginPage"
xHttp.setRequestHeader "Cookie", strCookie
xHttp.send strTicker

Excel VBA get data from web with msxml2.xmlhttp - how do I accept cookies automatically?

need your expertise and help, as i've looked around and couldn't find a solution:
I am uploading information to Excel from a website using the msxml2.xmlhttp method (did it earlier via webquery but it gets stuck after a few iterations plus it is slower). My problem is that now on every iteration, I have a Windows Security warning popping up asking me to accept a cookie from the website. Note that the website doesn't require a login/password. I understood from an earlier post that the msxml2.xmlhttp method strips cookies for security reasons, but I get the same message even if I change the method to winhttp. I also changed the settings in IE to accept all cookies automatically from the website but it didn't help.
My question is, what code do I need to add in order to have the cookies be accepted automatically, as I am looping this code on bulk and can't have it hang waiting for me to accept the cookie manually. Your help will be very much appreciated!!! Below is the code snippet (which I actually found here on Stackoverflow).
Set htm = CreateObject("htmlFile")
With CreateObject("msxml2.xmlhttp")
.Open "GET", "http://finance.yahoo.com/q/ae?s=" & Ticker & "+Analyst+Estimates", False
.send
htm.body.innerHTML = .responseText
End With
Set elemCollection = htm.getElementsByTagName("td")
For Each itm In elemCollection
If itm.className = "yfnc_tabledata1" Then
ActiveCell = itm.innerText
If ActiveCell.Column = 7 Then
ActiveCell.Offset(1, -6).Select
Else
ActiveCell.Offset(0, 1).Select
End If
End If
Next
I had the same problem this week.
After google and trying some ideas, I added two MsgBox statements to my code.
objXMLDoc.Open "GET", strURL, False
objXMLDoc.send
MsgBox "After XMLDoc.send", vbOKOnly, "Test"
objHTMLDoc.body.innerHTML = objXMLDoc.responseText
MsgBox "After .innerHTML assignment", vbOKOnly, "Test"
I found pop-up security warning windows always appear after .innerHTML assignment, i.e., the problem is nothing to do with XMLHttp. It is HTMLDocument, which causes the pop-ups.
I guess objHTMLDoc.body.innerHTML = objXMLDoc.responseText does not just do a simple value assignment. It must also trigged some action according to the contents of the webpage.
I checked the webpage and found some code like this:
YUI().use('node','event','event-mouseenter','substitute','oop','node-focusmanager','node','event','substitute','**cookie**','event-resize','node', 'event', 'querystring-stringify','node','event','node','event','event-custom','event-valuechange','classnamemanager','node', function(Y) {})
Then I changed my code as follows and the pop-up warning windows disappear.
objXMLDoc.Open "GET", strURL, False
objXMLDoc.send
objHTMLDoc.body.innerHTML = Replace(objXMLDoc.responseText, "cookie", "")
Hope this can be helpful if you still have the problem.

vbs script to send data and repeat

Does anyone have sample VBS code that sends a variable, waits response and repeat?
i have so far:
dim input
input = Inputbox ("Enter Var:" ,"Var sender...")
SourceURL = "http://example.com/someFunction.php?var="&input&""
that's it... my other code is not functional...
thanks in advance, hope anyone can help, totally lost in vbs... in windows in general...
Assuming that this is Windows Script Host, you can use the MSXML2 library.
do while true
Dim input, SourceURL
input = Inputbox ("Enter Var:" ,"Var sender...")
SourceURL = "http://www.google.co.uk/search?q=" & input
''// connect and send to server
Dim http: set http = CreateObject("MSXML2.XMLHTTP")
http.open "GET", SourceURL, false
http.send
if http.status = 200 then
''// do something with the return value if necessary
WScript.Echo http.responseText
else
''// problem?
end if
''// pause execution if you don't want to hit the server so often
WScript.Sleep 10
loop
if you're modifying things on the server, you should probably use a POST request instead of a GET request, but this should work if your server side script only accepts GET requests

Sending HTTP requests with VBA from Word

I am trying to send data from a Word document to a web page. I have found some code, pasted it into a new module, and saved it. When I run it I get "compile error, user defined type not defined"
My code:
Sub http()
Dim MyRequest As New WinHttpRequest
MyRequest.Open "GET", _
"http://www.google.com"
' Send Request.
MyRequest.Send
'And we get this response
MsgBox MyRequest.ResponseText
End Sub
A potential alternative to avoid having to select the library is to use an object i.e.
Sub http()
Dim MyRequest As Object
Set MyRequest = CreateObject("WinHttp.WinHttpRequest.5.1")
MyRequest.Open "GET", _
"http://www.google.com"
' Send Request.
MyRequest.Send
'And we get this response
MsgBox MyRequest.ResponseText
End Sub
You need to set a reference to Microsoft WinHTTP Services in your VBA Project (Tools -> References).
Here's what it would look like:
Also, you can read more about the Microsoft WinHTTP Services, version 5.1 here.
You will need to change your references (Tools=>References in the code window). Look for Microsoft WinHTTP Services, version 5.1 (or newer) and tick the box. If you are using Vista and office 2007, you may also need to register it first. Open a command window as administrartor and paste:
>regsvr32.exe "c:\windows\system32\winhttp.dll"
It should say if it works.