Referencing a Cell .send Syntax Error // Web Scraping - vba

Background/objective: Web Scrape: Problem with the Syntax using the .send
I am attempting to send the last name and first name from a list of names in two columns of cells, I am coming across Syntax Errors as it does not recognize the cell and assumes the range is the "name"
code:
The syntax error begins on the "last" and "first" line under the .send, as I am attempting to send a cell value rather than type in the name. What is the correct formatting when referencing a range of cells?
Option Explicit
Sub Test()
Dim sContent As String
Dim i As Long
Dim j As Long
Dim aHeader() As String
Dim aRows() As String
' Retrieve HTML content via XHR
With CreateObject("MSXML2.XMLHTTP")
.Open "POST", "http://npinumberlookup.org/getResults.php", False
.setRequestHeader "content-type", "application/x-www-form-urlencoded"
.send _
"last=Range(G:1)" & _
"&first=Range(F:1)" & _
"&pracstate=TX" & _
"&npi=" & _
"&submit=Search"

When you want to reference the value of a Range, is exactly as #Qharr said before. I tried doing:
' Retrieve HTML content via XHR
With CreateObject("MSXML2.XMLHTTP")
.Open "POST", "http://npinumberlookup.org/getResults.php", False
.setRequestHeader "content-type", "application/x-www-form-urlencoded"
.send _
"last=" & Range("G1").Value & _
"&first=" & Range("F1").Value & _
"&pracstate=TX" & _
"&npi=" & _
"&submit=Search"
End With
And it worked. No errors when running the code.

Related

Trying to Export the Data from Clockify

I have been trying to extract all the data from Clockify into Excel using VBA and using below code but there is no output coming with that code
Your help will be much appreciated.
Getting this reponse when run the code {"code":405,"message":"HTTP 405 Method Not Allowed"}
Public Sub GetAllProjects()
Dim httpCaller As MSXML2.XMLHTTP60
Set httpCaller = New MSXML2.XMLHTTP60
httpCaller.Open "GET", "https://reports.api.clockify.me/v1/workspaces/*****/reports/detailed"
httpCaller.setRequestHeader "X-Api-Key", CLOCKIFY_API_KEY
httpCaller.setRequestHeader "Content-Type", "application/json"
httpCaller.send
Debug.Print httpCaller.responseText
End Sub
A POST would look something like this in VBA:
Public Sub GetAllProjects()
Dim httpCaller As MSXML2.XMLHTTP60, body As String, obj As Object, json As Object, result
Dim ti As Object
'not sure how much of the request body is required....
'adjust dates below as needed
body = "{""dateRangeStart"": ""2020-05-10T00:00:00.000"", " & vbLf & _
" ""dateRangeEnd"": ""2020-05-16T23:59:59.000"", " & vbLf & _
" ""detailedFilter"": {""page"": 1,""pageSize"": 50}} "
Debug.Print body
Set httpCaller = New MSXML2.XMLHTTP60
With httpCaller
.Open "POST", "https://reports.api.clockify.me/v1/workspaces/*****/reports/detailed"
.setRequestHeader "X-Api-Key", CLOCKIFY_API_KEY
.setRequestHeader "Content-Type", "application/json"
.send body 'include JSON body
result = .responseText
Debug.Print "---Response---" & vbLf & result
End With
Set json = JsonConverter.ParseJson(result)
For Each obj In json("totals")
Debug.Print "------"
Debug.Print obj("totalTime")
Debug.Print obj("totalBillableTime")
Debug.Print obj("entriesCount")
Debug.Print obj("totalAmount")
Next obj
For Each obj In json("timeentries")
Debug.Print "------"
Debug.Print obj("_id")
Debug.Print obj("description")
'etc etc
'access the "timeinterval" sub-dictionary
Set ti = obj("timeInterval")
Debug.Print , ti("start")
Debug.Print , ti("end")
Debug.Print , ti("duration")
Next obj
End Sub

How to use ServerXMLHTTP60 and a client SSL certificate in Excel using VBA?

I cannot get it to work in VBA - Excel. I use the same header and XML-body in Postman - fine! Good response. I need to use a client certificate to identify myself, but I cannot get it done in VBA. The code needs to post some data (the XMLPostMessage) and then it receives some data from the server (a XML message as well).
The response I get from the server is a message in XML that has something to do with "Unidentified user". So, I do have communication, but it is not recognised as 'from a trusted party'. But using this certificate in Postman does give a good response.
== My VBA code: ==
Public Sub server()
Dim O As New ServerXMLHTTP60
Dim xmlDoc As New MSXML2.DOMDocument60
Dim XMLPostMessage As String
XMLPostMessage = "<WEB-UAS-AANVR>" & _
"<ALG-GEG>" & _
"<PROC-IDENT>3637</PROC-IDENT>" & _
"<PROC-FUNC>1</PROC-FUNC>" & _
"<INFO-GEBR>DITISEENTEST</INFO-GEBR>" & _
"</ALG-GEG>" & _
"<WEB-UAS-GEG>" & _
"<UAS-VRR-EXAMEN-GEG>" & _
"<UAS-VRR-EX-INST></UAS-VRR-EX-INST>" & _
"<UAS-VRR-EX-SRT>A2</UAS-VRR-EX-SRT>" & _
"<UAS-VRR-EX-DAT>20211210</UAS-VRR-EX-DAT>" & _
"<GEB-DAT-UAS-VRR>19840726</GEB-DAT-UAS-VRR>" & _
"<UAS-VRR-EX-REF>#12345</UAS-VRR-EX-REF>" & _
"</UAS-VRR-EXAMEN-GEG>" & _
"</WEB-UAS-GEG>" & _
"</WEB-UAS-AANVR>"
With O
.Open "POST", "https://<the serverpath goes here>", False
.setRequestHeader "Content-type", "application/xml"
.setRequestHeader "Content-type", "text/xml"
.setRequestHeader "Charset", "UTF-8"
.setOption 3, "<The Friendly Name of the certificate goes here>"
' .setOption 3, "CURRENT_USER\My\<The Friendly Name of the certificate goes here>"
.send XMLPostMessage
xmlDoc.LoadXML (O.responseXML.XML)
Debug.Print xmlDoc.XML
If Not .Status = 200 Then
MsgBox "UnAuthorized. Message: " & .Status & " - " & .statusText
Exit Sub
End If
End With
Set O = Nothing
End Sub

VBA HTTP Request POST returning empty string

I am working on a procedure, in MS-Access VBA, to POST an XML text string to a web service and process the XML text string that is returned from the service.
The issue I am having is that the responseText property is always empty when it should contain a XML text string. No errors are returned and the .status = "OK".
I have tried the WinHttp.WinHttpRequest, MSXML2.XMLHTTP, and MSXML2.ServerXMLHTTP objects and consistently have the same issue.
Here is a code example:
Public Function Send() As Boolean
Dim oXHR As MSXML2.XMLHTTP60
Dim sURL, sCred As String
Dim sRequest, sResult, sStatus, sHeader As String
Dim bRtn As Boolean
BuildReqXML
sRequest = Me.RequestXML_String
With orsValues
sURL = .Fields("WebServiceURL").Value
sCred = Base64Encode(Trim(.Fields("User").Value) & ":" & Trim(.Fields("Password").Value))
End With
Set oXHR = New MSXML2.XMLHTTP60
With oXHR
.Open "POST", sURL, False
.SetRequestHeader "Authorization", "Basic " & sCred & """"
.SetRequestHeader "User-Agent", "Mozilla/4.0"
.SetRequestHeader "Content-Type", "text/xml"
.Send sRequest
sStatus = .StatusText
sResult = .ResponseText
sHeader = .GetAllResponseHeaders
If sResult <> "" Then
If Contains(sResult, "<") Then ReadXML sResult, "Response"
Debug.Print sResult
Else
Debug.Print sHeader
Debug.Print sRequest
End If
End With
Set oXHR = Nothing
End Function
I have verified that the web service is working correctly by building a similar call in a HTML document, sending the XML string, and receiving the response XML string.
Can someone please help me fix my issue?
I found the problem, with help from Fiddler.
The line setting the authorization header
.SetRequestHeader "Authorization", "Basic " & sCred & """"
Was adding a (") to the header line. The corrected line is
.SetRequestHeader "Authorization", "Basic " & sCred
Thank you for your help

How to reference a Value in .Open "Get" statement Statment in VBA

I got referenced value in my sub, but I want to use my referenced value within the GET statement.
I want to use my num1 value as my destaination = in my .Open "Get" statement.
Dim num1 As String
Set htm = CreateObject("htmlFile")
num1 = Cells(2, 2).Value
With CreateObject("msxml2.xmlhttp")
.Open "GET", "https://maps.googleapis.com/maps/api/distancematrix/json?origins=sy10 5tp&destinations='num1'&mode=driving&language=en-GB&v=3&sensor=fals", False
Many Thanks.
Close the quoted string literal with " and use the & concatenation operator to append the variable:
x = "abc" & stringVariable & "def"
So
.Open "GET", "https://maps.googleapis.com/maps/api/distancematrix/json?origins=sy10 5tp&destinations=" & num1 & "&mode=driving&language=en-GB&v=3&sensor=fals", False
(You also have fals which presumably should be false)

Upload Excel xlsm file to php script using VBA

I would like to upload an Excel xlsm file to a php script from VBA. I found the following code:
Dim WinHttpReq As Object
Set WinHttpReq = CreateObject("WinHttp.WinHttpRequest.5.1")
Dim strURL As String
Dim StrFileName As String
Dim FormFields As String
Dim path As String
Dim name As String
StrFileName = "c:\temp\ctc1output.xls"
strURL = "http://www.tri-simulation.com/P3/"
WinHttpReq.Open "POST", strURL, False
' Set the header
WinHttpReq.SetRequestHeader "Content-Type", "application/x-www-form-urlencoded"
FormFields = """fileulp=" & StrFileName & """"
FormFields = FormFields + "&"
FormFields = FormFields + """sfpath=P3"""
WinHttpReq.Send FormFields
' Display the status code and response headers.
MsgBox WinHttpReq.GetAllResponseHeaders
MsgBox WinHttpReq.ResponseText
Should I handle the file as a binary file or another type of file?
Can I upload the file while it is still open (I want to upload the file from which the VBA is running from)?
I am not sure if I'm on the right track.
I'm also not sure about what the headers and form fields should be.
Thx for any help.
You won't need to base64 encode anything. Follow the sample code you have found but before preparing the file (before '---prepare body comment) just add your other texts (form entries) like this
sPostData = sPostData & "--" & STR_BOUNDARY & vbCrLf & _
"Content-Disposition: form-data; name=""" & Name & """"
sPostData = sPostData & vbCrLf & vbCrLf & _
pvToUtf8(Value) & vbCrLf
... where Name and Value are the designed name and the actual text that you want to include in service request. For the function pvToUtf8 implementation take a look at this Google Cloud Print service connector. The snippet above is taken from pvRestAddParam function of the same connector.