Sending HTTP requests with VBA from Word - vba

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.

Related

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

how to do http request using libreoffice basic macros

I want to write a macro on a LibreOffice spreadsheet, to send an HTTP request to an web URL and receive a JSON like response. Can i do it with LibreOffice basic macro programming? Where can i get information about the API.
I really appreciate any tips.
Thanks
I'm too late to help Antonio, but for posterity...
You can call spreadsheet functions from Basic, as explained in the open office docs. Here's a simple example that invokes the WEBSERVICE() function:
Function GetWebContent(url As string) As String
On Error GoTo ErrorHandler
Dim funtionAccess As Object
functionAccess = createUnoService("com.sun.star.sheet.FunctionAccess")
GetWebContent = functionAccess.callFunction("WEBSERVICE",Array(url))
Exit Function
ErrorHandler:
GetWebContent = "Error " & Err
End Function
Function Test
Dim url As String
url = "http://www.google.com"
Dim response As String
response = GetWebContent(url)
End Function

How to check Sharepoint Document Properties using VBA

I am looking to develop code to view the document properties of a file on SharePoint, then later build out this code to see if it matches the document properties of the ActiveWorkbook. Below is a sample of the code I have so far which is able to filter through to the correct document in the SharePoint Library. Does anyone know the function which must be added to objFile to access the SharePoint Document properties?
Sub CheckVersion()
Dim FSO As Object
Set FSO = CreateObject("Scripting.FileSystemObject")
Dim objFile As Object
Dim objDSO As Object
For Each objFile In FSO.GetFolder("\\SharePoint\Library\").Files
If objFile.Name = "FileName.zip" Then
MsgBox (objFile.Properties.Title)
End If
Next
End Sub
I am assuming SharePoint 2010 and higher version.
Use SharePoint REST Services to get proper data items with desired properties.
REST Services Reference for Sharepoint 2010
REST API Reference for SharePoint 2013
Get items from list using SharePoint 2010:
http://lab/_vti_bin/listdata.svc/List1()?$filter=startswith(Title,'foo')&$top=1&$select=Title,Column2,Column3
Get items from list using SharePoint 2013
http://lab/_api/web/lists/getbytitle('List1')/items?$filter=startswith(Title,'foo')&$top=1&$select=Title,Column2,Column3
Then you have to request this url with VBA (remeber to add references to Microsoft WinHTTP Services, version 5.1 and Microsoft XML, v6.0)
URL = "http://lab/_vti_bin/listdata.svc/List1()?$filter=startswith(Title,'foo')&$top=1&$select=Title,Column2,Column3"
Set req = CreateObject("WinHttp.WinHttpRequest.5.1")
req.Open "GET", URL, False
req.setRequestHeader "Content-Type", "application/xml"
req.SetCredentials "login", "pass", 0
req.Send
Set objXML = CreateObject("Msxml2.DomDocument.6.0")
If Not objXML.LoadXML(req.ResponseText) Then
Err.Raise objXML.parseError.ErrorCode, , objXML.parseError.reason
End If
XML parsing is for you ;)
/edit
To filter element with your filename, use:
http://lab/_vti_bin/listdata.svc/Library()?$filter=FileLeafRef eq 'FileName.zip'&$select=Title

VBA Kerberos Authentication

I want to send a POST request to a Java servlet with VBA using the Kerberos ticket from the Windows Log In for authentication and then retrieve a JSON response from the servlet. Can I achieve this without using an InternetExplorer object, e.g. using WinHttpRequest?
WinHttpRequest is not an IE object. The above described usecase works perfectly as long as you set up to relax the security permissions. I have implemented a proof of concept last year: Excel, VBA, REST, Tomcat, SPNEGO authentication.
Stub code:
Dim winHttp As Object
Set winHttp = CreateObject("WinHttp.WinHttpRequest.5.1")
winHttp.SetAutoLogonPolicy (0)
winHttp.Open "GET", "http://..."
winHttp.send
Dim success As Boolean
success = winHttp.waitForResponse(5)
If Not success Then
Debug.Print "DOWNLOAD FAILED!"
Exit Sub
End If
Dim responseText As String
responseText = winHttp.responseText

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.