Compilation Error with small script - vba

I'm trying to write a cls in Excel 2007, here's the code:
Dim JiraService As MSXML2.XMLHTTP60
Set JiraService = New MSXML2.XMLHTTP60
JiraService.Open "GET", "URL", False
JiraService.SetRequestHeader "Content-Type", "application/json"
JiraService.SetRequestHeader "Accept", "application/json"
JiraService.Send
sRestResponse = JiraService.ResponseText
MsgBox sRestResponse
I'm getting a compilation error, indicating that Set appears to be invalid.
It basically says that the external procedure is not valid.
Can anyone help me out?

You are missing the appropriate reference I guess. Click on Tools~~>References in VBA
Add a project references to;
Microsoft WinHTTP Services, version 5.1
Microsoft XML, v6.0
Also in this line
JiraService.Open "GET", "URL", False
If URL is the variable which holds the actual URL then "URL" will be considered as a string and not a variable since it is between quotes. I guess you are trying this?
JiraService.Open "GET", URL, False
FOLLOWUP (From Comments)
The problem is that you have pasted the above code in a class module. You are suppose to paste the code in a module and call it in a sub. See this example
Sub Sample()
Dim JiraService As MSXML2.XMLHTTP60
Set JiraService = New MSXML2.XMLHTTP60
JiraService.Open "GET", URL, False
JiraService.SetRequestHeader "Content-Type", "application/json"
JiraService.SetRequestHeader "Accept", "application/json"
JiraService.Send
sRestResponse = JiraService.ResponseText
MsgBox sRestResponse
End Sub
Screenshot

Related

Create Sharepoint folder from VBA (access 2016)

I have an access 2016 app that currently creates a folder on a shared drive related to the DB record the user is working on.
We are migrating to SP online and I need to re-create something similar
I can list the files and folders currently in a directory using the API but when I try and create a new folder I am getting an error
"{"error":{"code":"-2130575251, Microsoft.SharePoint.SPException","message":{"lang":"en-US","value":"The security validation for this page is invalid and might be corrupted. Please use your web browser's Back button to try your operation again."}}}"
The only thing I can see I am doing differently is I am not including a Authorization: "Bearer " + accessToken header in the post.
I haven't been including it in the gets for the Files list and it is working using the cached credentials from IE.
Getting the file and folder like this is working
'create XML HTTP object
Set objXMLHTTP = CreateObject("MSXML2.XMLHTTP")
With objXMLHTTP
'open connection to site
.Open "GET", url, False
'.send
.setRequestHeader "Content-Type", "application/json; charset=UTF-8"
.setRequestHeader "Accept", "application/json"
.send
Do Until .ReadyState = 4: DoEvents: Loop
sJSONString = .responseText
End With
Dim Json As Object
Set Json = JsonConverter.ParseJson(sJSONString)
Debug.Print JsonConverter.ConvertToJson(Json, Whitespace:=2)
Dim value As Dictionary
For Each value In Json("value")
Debug.Print "> " + value("Name")
Next value
However trying to create a folder fails
strPostData = "{ '__metadata': { 'type': 'SP.Folder' }, 'ServerRelativeUrl': '/Shared Documents/Folder1'}"
'Set objXMLHTTP = New MSXML2.XMLHTTP
With objXMLHTTP
.Open "POST", url, False
.setRequestHeader "accept", "application/json;odata=verbose"
.setRequestHeader "Content-Type", "application/json;odata=verbose"
.send strPostData
strResponse = .responseText
End With
Can anyone advise if what I am trying is possible and if so what I am doing is wrong?
Sorry, almost immediately I found and answer!
Needed to add
.setRequestHeader "X-RequestDigest", digest
.setRequestHeader "Content-Length", Len(strPostData)
and it all started working!
Thanks anyway, hope this helps someone else

Web Scraping using VBA and MSXML2.XMLHTTP library

I'm trying to scrap data from a website using MSXML2.XMLHTTP object on VBA environment (Excel) and I cannot figure out how to solve this problem! The website is the following:
http://www.detran.ms.gov.br/consulta-de-debitos/
You guys can use the following test data to fill the form:
Placa: oon5868
Renavam: 1021783231
I want to retrieve data like "chassi", with the data above that would be " 9BD374121F5068077".
I do not have problems parsing the html document, the difficult is actually getting the information as response! Code below:
Sub SearchVehicle()
Dim strPlaca As String
Dim strRenavam As String
strPlaca = "oon5868"
strRenavam = "01021783231"
Dim oXmlPage As MSXML2.XMLHTTP60
Dim strUrl As String
Dim strPostData As String
Set oXmlPage = New MSXML2.XMLHTTP60
strUrl = "http://www2.detran.ms.gov.br/detranet/nsite/veiculo/veiculos/retornooooveiculos.asp"
strPostData = "placa=" & strPlaca & "&renavam=" & strRenavam
oXmlPage.Open "POST", strUrl, False
oXmlPage.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
oXmlPage.send strPostData
Debug.Print oXmlPage.responseText
End Sub
The strURL used in the POST method ".../retornooooveiculos.asp" is the one google developer tools and fiddler showed me that was the correct address the website was posting the payload.
When manually accessed, the website retrieve the correct information, but running my code I always get the following response on the .responseText:
<html>Acesse: <b><a href='http://www.detran.ms.gov.br target='_parent'>www.detran.ms.gov.br</a></b></html>
HELP PLEASE, I'm getting crazy trying to solve this puzzle! Why do I get redirected like this?
I need the "CHASSI" information and can't find the correct http Request to do this!
Try the below approach. It should fetch you the content you are after. The thing is you need to supply the Cookie copied from your Request Headers fields in order for your script to work which you can find using devtools.
Sub SearchVehicle()
Const URL As String = "http://www2.detran.ms.gov.br/detranet/nsite/veiculo/veiculos/retornooooveiculos.asp"
Dim HTTP As New ServerXMLHTTP60, HTML As New HTMLDocument
Dim elem As Object, splaca$, srenavam$, qsp$
splaca = "oon5868"
srenavam = "01021783231"
qsp = "placa=" & splaca & "&renavam=" & srenavam
With HTTP
.Open "POST", URL, False
.setRequestHeader "User-Agent", "Mozilla/5.0"
.setRequestHeader "Cookie", "ISAWPLB{07D08995-E67C-4F44-91A1-F6A16337ECD6}={286E0BB1-C5F9-4439-A2CE-A7BE8C3955E0}; ASPSESSIONIDSCSDSCTB=AGDPOBEAAPJLLMKKIGPLBGMJ; 69137927=967930978"
.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
.send qsp
HTML.body.innerHTML = .responseText
End With
For Each elem In HTML.getElementsByTagName("b")
If InStr(elem.innerText, "Chassi:") > 0 Then MsgBox elem.ParentNode.NextSibling.innerText: Exit For
Next elem
End Sub
Once again: fill in the Cookie field by collecting it using your devtools (from Request Headers section), if for some reason my provided Cookie doesn't work for you. Thanks.
Output I'm getting:
9BD374121F5068077

Excel VBA MSXML2 Post response body empty runtime error -2147467260

I would like to post data to Jira using this method :
Private IEService As New MSXML2.XMLHTTP60
Public Function httpPOST(baseUrl As String, url As String, jsonInput As String, auth As String) As String
Dim accept As String
accept = "application/json"
With IEService
.Open "POST", baseUrl & url, False
.setRequestHeader "Content-Type", "application/json"
.setRequestHeader "Accept", accept
.setRequestHeader "Authorization", "Basic " & auth
.setRequestHeader "Origin", baseUrl
.send jsonInput
httpPOST = .responseText
'MsgBox (.responseText)
End With
End Function
Data is fine and the POST is executed on the back end side. But Jira in this instance returns an empty response body.
When this happens VBA crashes on .send jsonInput with error : runtime error -2147467260
Seems like MSXML2 does not handle empty responses. But I haven't found anyone facing same issue searching on the web.
Any ideas what I am doing wrong or how to fix it ?
Thanks

Getting "method not valid without suitable object" error when trying to make a HTTP request in VBA?

I tried to follow this example: http://libkod.info/officexml-CHP-9-SECT-5.shtml - Archive.org - Donate
but it gave this error
on this line:
Dim objHTTP As New MSXML2.XMLHTTP
I tried to use this example: How can I send an HTTP POST request to a server from Excel using VBA?
but it gave this error:
on this line:
Print objHTTP.Status
So how do I make a POST REST call in VBA? How do I make a PUT multi-part/form-data file upload REST call in VBA?
Tools > References
Code
Sub SendEmail()
'Dim objHTTP As New MSXML2.XMLHTTP
'Set objhttp = CreateObject("WinHttp.WinHttpRequest.5.1")
Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")
URL = "http://localhost:8888/rest/mail/send"
objHTTP.Open "POST", URL, False
objHTTP.send ("{""key"":null,""from"":""me#me.com"",""to"":null,""cc"":null,""bcc"":null,""date"":null,""subject"":""My Subject"",""body"":null,""attachments"":null}")
Print objHTTP.Status
Print objHTTP.ResponseText
End Sub
Reference
WinHttpRequest object: http://msdn.microsoft.com/en-us/library/windows/desktop/aa384106(v=vs.85).aspx
You probably haven't added a reference to Microsoft XML (any version) for Dim objHTTP As New MSXML2.XMLHTTP in the VBA window's Tools/References... dialog.
Also, it's a good idea to avoid using late binding (CreateObject...); better to use early binding (Dim objHTTP As New MSXML2.XMLHTTP), as early binding allows you to use Intellisense to list the members and do all sorts of design-time validation.
I had to use Debug.print instead of Print, which works in the Immediate window.
Sub SendEmail()
'Dim objHTTP As New MSXML2.XMLHTTP
'Set objHTTP = New MSXML2.XMLHTTP60
'Dim objHTTP As New MSXML2.XMLHTTP60
Dim objHTTP As New WinHttp.WinHttpRequest
'Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
'Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")
URL = "http://localhost:8888/rest/mail/send"
objHTTP.Open "POST", URL, False
objHTTP.setRequestHeader "Content-Type", "application/json"
objHTTP.send ("{""key"":null,""from"":""me#me.com"",""to"":null,""cc"":null,""bcc"":null,""date"":null,""subject"":""My Subject"",""body"":null,""attachments"":null}")
Debug.Print objHTTP.Status
Debug.Print objHTTP.ResponseText
End Sub
Check out this one:
https://github.com/VBA-tools/VBA-Web
It's a high level library for dealing with REST. It's OOP, works with JSON, but also works with any other format.
For reading REST data, at least OData Consider Microsoft Power Query. You won't be able to write data. However, you can read data very well.

How to browse through box.com folders to select a file and download the selected file

I need a excel macro (vba) to select a file from box.com by iterating though existing folders and at the same time I need to upload the file from my machine to box.com folder using excel macro. I am searching for a long time on net. But no use. Please help or try to give some ideas how to achieve this.
Thanks in advance.
-Edit
I am using the below code for getting authentication token. But I am getting an error message at the place of .send(url). Error message is "The server name or address could not be resolved".
Function getAuthToken()
Dim WinHttpReq As WinHttp.WinHttpRequest
Dim api_key As String
api_key = "{api_key}"
Set WinHttpReq = New WinHttp.WinHttpRequest
strUrl = "https://www.box.net/api/1.0/rest?action=get_ticket&api_key=" & api_key
WinHttpReq.Open Method:="GET", url:=strUrl, async:=False
WinHttpReq.Send
getTicket = WinHttpReq.responseText
Debug.Print getTicket
End Function
Not being a vba expert, I suspect that you'll get more answers if you tag your question with a vba tag. However, some quick scanning around shows that vba can call REST apis by doing something like this:
Dim MyURL as String
MyURL = "http://api.box.com/2.0/folders/0.xml"
Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")
With objHTTP
.Open "GET", MyURL, False
.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
.setRequestHeader "Authorization", "BoxAuth api_key=<your api key>&auth_token=<your auth token>
.send (MyURL)
End With
I'll defer to a real VBA expert, but something roughly along these lines should work.
Yeah, this is frustrating. I tried code like Peter's using both WinHttp.WinHttpRequest.5.1 and MSXML2.ServerXMLHTTP and with both I just get a zero-length string back. No error message or anything.
I installed cURL and tested the URL. It works fine there. The script below also works fine with a generic JSON web service, like jsonplaceholder.typicode.com.
All this makes me think that Box.com is receiving the message, detecting it is coming from a non-approved source, and returning nothing . . . probably for security reasons.
Option Explicit
Const URL As String = "https://api.box.com/2.0/folders/0 -H ""Authorization: Bearer MyToken"""
'Const URL As String = "https://jsonplaceholder.typicode.com/posts/1"
Sub Test()
Dim winHTTP As Object
' Set winHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
Set winHTTP = CreateObject("MSXML2.ServerXMLHTTP")
winHTTP.Open "GET", URL
winHTTP.setRequestHeader "Content-Type", "application/json"
winHTTP.send
Debug.Print winHTTP.ResponseText
If Len(winHTTP.ResponseText) = 0 Then
MsgBox "blank string returned"
Else
Dim objResponse As Object
Set objResponse = JsonConverter.ParseJson(winHTTP.ResponseText) 'Converter from Tim Hall - https://github.com/VBA-tools/VBA-JSON
End If
End Sub