Unable to create SharePoint item & update external columns content (business connectivity services)? - excel

I am having trouble creating a new item within a SharePoint 2013 list. I'm able to actually create the item, though the external data (business connectivity services [bcs]) does not autopopulate as it would during the creation of the item via the SharePoint UI. Is there any way to actually make this work, or to send the function that needs to run via POST? I've pasted my current item creation sub below.
Dim oXMLHTTP As Object
Dim sListNameOrGuid As String
Dim sBatchXml As String
sWTF As String
Set oXMLHTTP = CreateObject("MSXML2.XMLHTTP.6.0")
sCurrentUser = fGetUserID
With oXMLHTTP
.Open "POST", "MYSPSITE.COM/_api/web/lists/GetByTitle('THELIST')/items", True
.setRequestHeader "Accept", "application/json;odata=verbose"
.setRequestHeader "Content-Type", "application/json;odata=verbose"
' .setRequestHeader "X-HTTP-Method", "PATCH"
' .setRequestHeader "If-Match", "*"
.setRequestHeader "X-RequestDigest", fGetLoginToken
sWTF = "{ 'User': " & Int(sCurrentUser) & ", 'newComment': 'TESTING TESTING'}"
.send (sWTF)
Do While .readyState <> 4:
DoEvents
Loop
Debug.Print (.responseText)
.abort
End With
Set oXMLHTTP = Nothing
End Sub

Lower the timer job frequency.

Related

Google Translate via VBA setting for accept-encoding

I'm trying to use the google translate API via VBA (works in python so far), and I found that the only difference between the python request and the VBA one is on the header "accept-encoding", the python one uses the "application/gzip" and works, but the VBA one is automatically changed to "gzip,deflate" even if I change it through code. Here is the code:
Function Test_GoogleTranslate()
Dim strTranslate As String
Dim objRequest As Object
Dim strUrl As String
Dim blnAsync As Boolean
Dim strResponse As String
Dim strWeather As String
Dim payload As String
Set objRequest = CreateObject("MSXML2.XMLHTTP")
payload = "target=es&q=something&source=en"
strTranslate = "https://google-translate1.p.rapidapi.com/language/translate/v2"
strTranslate = strTranslate & "?" & payload
With objRequest
.Open "POST", strTranslate, True
.setRequestHeader "host", "google-translate1.p.rapidapi.com"
.setRequestHeader "x-forwarded-port", "443"
.setRequestHeader "x-forwarded-proto", "https"
.setRequestHeader "connection", "keep-alive"
.setRequestHeader "content-type", "application/x-www-form-urlencoded"
.setRequestHeader "accept-encoding", "application/gzip"
.setRequestHeader "x-rapidapi-host", "google-translate1.p.rapidapi.com"
.setRequestHeader "x-rapidapi-key", "856e8ba78dmsh443766612c5a923p14f661jsn72323e803261"
.Send
While objRequest.readyState <> 4
DoEvents
Wend
strResponse = .ResponseText
End With
MsgBox (strResponse)
End Function
When I changed the accept-encoding to "gzip, deflate" in python it crashed, so I figured that might be the problem.
Any help is greatly appreciated
I had some success with Google Translate and Excel VBA using the MSXML2.ServerXMLHTTP object. I note you are using MSXML2.XMLHTTP. The solution appears to work well only setting a User-Agent request header so I did not delve into accept-encoding etc.
The differences between MSXML2.ServerXMLHTTP and MSXML2.XMLHTTP are touched upon in this question which might be useful for you.
Working code using MSXML2.ServerXMLHTTP:
Option Explicit
Sub Test()
Debug.Print Translate("Hello", "en", "fr", True) ' french
Debug.Print Translate("Hello", "en", "de", True) ' german
Debug.Print Translate("Hello", "en", "pt", True) ' portuguese
Debug.Print Translate("Hello", "en", "ru", False) ' russian - use romanised alphabet
Debug.Print Translate("Hello", "en", "ru", True) ' russian - use cyrillic
' ThisWorkbook.Sheets(1).Range("A1").Value = Translate("Hello", "en", "ru", True)
Debug.Print Translate("Hello", "en", "zh-CN", False) ' chinese simplified - use romanised alphabet
Debug.Print Translate("Hello", "en", "zh-CN", True) ' chinese simplified - use chinese script
' ThisWorkbook.Sheets(1).Range("B1").Value = Translate("Hello", "en", "zh-CN", True)
End Sub
Public Function Translate(strInput As String, strFromLanguageCode As String, strToLanguageCode As String, blnTargetAlphabet As Boolean) As String
Dim strURL As String
Dim objHTTP As Object
Dim objHTML As Object
Dim objDivs As Object, objDiv
Dim strTranslatedT0 As String
Dim strTranslatedO1 As String
' send query to web page
strURL = "https://translate.google.com/m?hl=" & strFromLanguageCode & _
"&sl=" & strFromLanguageCode & _
"&tl=" & strToLanguageCode & _
"&ie=UTF-8&prev=_m&q=" & strInput
Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")
objHTTP.Open "GET", strURL, False
objHTTP.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
objHTTP.send ""
' create a html document
Set objHTML = CreateObject("htmlfile")
With objHTML
.Open
.Write objHTTP.responseText
.Close
End With
' o1 has Anglicised translation, t0 as tranlsation in target language
Set objDivs = objHTML.getElementsByTagName("div")
For Each objDiv In objDivs
If objDiv.className = "o1" Then
strTranslatedO1 = objDiv.innerText
End If
If objDiv.className = "t0" Then
strTranslatedT0 = objDiv.innerText
End If
Next objDiv
' choose which to return
If blnTargetAlphabet Then
Translate = strTranslatedT0
Else
Translate = strTranslatedO1
End If
CleanUp:
Set objHTML = Nothing
Set objHTTP = Nothing
End Function
Result:
Bonjour
Hallo
Olá
Privet
??????
Ni hao
??
The VBA immediate window doesn't print Cyrillic or Chinese characters but you can see this feature working by outputing to a cell:
December 2020 update
Looks like this method will no longer work going back maybe to mid November.
Looking at the response
the div class names have changed to something more obscure
there's some esoteric c-wiz elements doing something wonderful...
also, I suspect that some client side script is calling for the actual translation after the document is retrieved
Options: Selenium, Microsoft Translate, free and paid tiers for Google translation APIs ;)

VBA- Unable to update SharePoint 2013 item via REST API

I am attempting to update a SharePoint item via REST API, though I am receiving the below error:
{"odata.error":{"code":"-1, System.InvalidOperationException","message":{"lang":"en-US","value":"The type of data at position 0 is different than the one expected."}}}
I'm not quite sure what is causing this- I have the request type set to JSON, but it does not seem to accept my input. Any help is appreciated :-)
My code:
Sub Work_Damn_You()
Dim oXMLHTTP As Object
Dim sListNameOrGuid As String
Dim sBatchXml As String
Dim sSoapBody As String
Dim sWTF as string
Set oXMLHTTP = CreateObject("MSXML2.XMLHTTP.6.0")
sListNameOrGuid = sListName
With oXMLHTTP
.Open "POST", "http://SPSITE.COM/_api/web/lists/GetByTitle('PAGE')/items(22)", True
.setRequestHeader "X-RequestDigest", testerino
.setRequestHeader "Accept", "application/json;odata=nometadata"
.setRequestHeader "Content-Type", "application/json;odata=verbose"
.setRequestHeader "__metadata", "(""type"":""SP.Data.QATrackerListItem"""
sWTF = """preTestComment""=""Hello"""
.send (sWTF)
Debug.Print (.responseText)
' Check response
If .Status = 200 Then
Debug.Print .Status & " [Happy Days!]"
Else
Debug.Print .Status & " [Sad Days :-(]"
End If
End With
Set oXMLHTTP = Nothing
End Sub
'''

Attempting to set HTML element object by using getElementsByID returns nothing; ID exists in HTML page [duplicate]

Thanks to the help and code from #QHarr I have got the tracking info from Fedex, DHL and Startrack working. I have been trying to use his code and the UPS tracking Web Service Developer Guide and Tracking JSON Developer Guides to get UPS to work as well within Excel. The JSON converter code is from here https://github.com/VBA-tools/VBA-JSON/blob/master/JsonConverter.bas
The code I have tried is as follows
Public Function GetUPSDeliveryDate(ByVal id As String) As String
Dim body As String, json As Object
body = "data={""TrackPackagesRequest"":{""appType"":""WTRK"",""appDeviceType"":""DESKTOP"",""supportHTML"":true,""supportCurrentLocation"":true,""uniqueKey"":"""",""processingParameters"":{},""trackingInfoList"":[{""trackNumberInfo"":{""trackingNumber"":" & Chr$(34) & id & Chr$(34) & ",""trackingQualifier"":"""",""trackingCarrier"":""""}}]}}"
body = body & "&action=trackpackages&locale=en_AU&version=1&format=json"
With CreateObject("MSXML2.XMLHTTP")
.Open "POST", "http://wwwapps.ups.com/WebTracking", False
.setRequestHeader "Referer", "https://www.ups.com/track?loc=en_AU&tracknum=" & id
.setRequestHeader "User-Agent", "Mozilla/5.0"
.setRequestHeader "X-Requested-With", "XMLHttpRequest"
.setRequestHeader "Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"
.send body
Set json = JSONConverter.ParseJson(.responseText)
End With
GetUPSDeliveryDate = Format$(json("ResponseStatus")("ShipmentType")(1)("DeliveryDate"), "dddd, mmm dd, yyyy")
End Function
I am not getting any errors in the code per-say, but when I use the =GetUPSDeliveryDate() function I am getting a #VALUE! response instead of the delivered date of 7th May 2019, so I am guessing I have got the following bit wrong
GetUPSDeliveryDate = Format$(json("ResponseStatus")("ShipmentType")(1)("DeliveryDate"), "dddd, mmm dd, yyyy")
I have also tried the following, but no luck.
If json("results")(1)("delivery")("status") = "delivered" Then
GetUPSDeliveryDate = json("results")(1)("checkpoints")(1)("date")
Else
GetUPSDeliveryDate = vbNullString
End If
A sample UPS tracking number is 1Z740YX80140148107
Any help would be greatly appreciated.
Thanks
The following is by mimicking of this UPS tracking site. The json parser used is jsonconverter.bas: Download raw code from here and add to standard module called jsonConverter . You then need to go VBE > Tools > References > Add reference to Microsoft Scripting Runtime.
Option Explicit
Public Sub test()
Debug.Print GetUPSDeliveryDate("1Z740YX80140148107")
End Sub
Public Function GetUPSDeliveryDate(ByVal id As String) As String
Dim body As String, json As Object
body = "{""Locale"":""en_US"",""TrackingNumber"":[""" & id & """]}"
With CreateObject("MSXML2.XMLHTTP")
.Open "POST", "https://www.ups.com/track/api/Track/GetStatus?loc=en_US", False
.setRequestHeader "Referer", "https://www.ups.com/track?loc=en_US&requester=ST/"
.setRequestHeader "User-Agent", "Mozilla/5.0"
.setRequestHeader "DNT", "1"
.setRequestHeader "Content-Type", "application/json"
.setRequestHeader "Accept", "application/json, text/plain, */*"
.send body
Set json = JsonConverter.ParseJson(.responseText)
End With
If json("trackDetails")(1)("packageStatus") = "Delivered" Then
GetUPSDeliveryDate = json("trackDetails")(1)("deliveredDate")
Else
GetUPSDeliveryDate = "Not yet delivered"
End If
End Function
The Tracking Web Service Developer Guide.pdf contains all you need to know to set up using the official tracking API.

How to Send Variables on .SetRequestData on Excel VBA

I'm working on a API integration on my Excel WorkSheet using VBA and I'm trying to send user input on a cell sent to a RequestHeader in order to find a product on the server
I've tried importing the data directly from the sheet onto a string and then sending that string as the value for the header but I can't seem to get it to work. I'm new to this whole VBA stuff so I don't honestly know if that's possible. Here's what I've tried:
Sub GetCompanyInformation()
Dim hReq As Object, JSON As Dictionary
Dim i As Long
Dim var As Variant
Dim ws As Worksheet
Set ws = Sheet1
'create our URL string and pass the user entered information to it
Dim strUrl As String
strUrl = "My API URL Goes Here"
Dim cod As String
cod = ws.[MYCELL]
Set hReq = CreateObject("MSXML2.XMLHTTP")
With hReq
.Open "GET", strUrl, False
.SetRequestHeader "cache-control", "no-cache"
.SetRequestHeader "data_filter", ""
.SetRequestHeader "data", "products"
.SetRequestHeader "data_id", cod
.Send
End With
[...]
It returns me an empty string. However if I send the request with the same number I add on my cell as such:
[...]
Set hReq = CreateObject("MSXML2.XMLHTTP")
With hReq
.Open "GET", strUrl, False
.SetRequestHeader "cache-control", "no-cache"
.SetRequestHeader "data_filter", ""
.SetRequestHeader "data", "products"
.SetRequestHeader "data_id", "1234"
.Send
End With
It Works, and it returns me the data I need. Am I doing something wrong? Can I get the variable data on a Request Header?

Trying to get for searching lattitude and longitude of places using vba from a web page. find button clicking through vba is not working

When executing this code it is filling the required text box on the website but pressing the find button gives the output 'not found' in the message box.
Subsequently, if i manually just click in the text box on the filled value and then click the find button, it shows the desired result.
How can I make this work?
Public Sub experiment()
Dim ie As InternetExplorer
Set ie = New InternetExplorer
ie.navigate "https://www.latlong.net/"
Do
DoEvents
Loop Until ie.readyState = READYSTATE_COMPLETE
Dim doc As HTMLDocument
Set doc = ie.document
Dim inputElement As HTMLInputElement
Set inputElement = doc.getElementsByClassName("width70")(0)
inputElement.Value = "Delhi Airport, India"
ie.Visible = True
doc.getElementById("btnfind").Click
Do
DoEvents
Loop Until ie.readyState = READYSTATE_COMPLETE
End Sub
Rather than IE automation and interacting with the page as a user would, the code below should emulate the request triggered by the 'Find' button on the page, but you need to assign a value to placeName in the code (currently it is "Delhi Airport, India").
If you are interested in only the co-ordinates (and no other information on the rest of the page), then this approach might be okay for you.
You'll need to add a reference (Tools > References > Scroll down and tick Microsoft XML, v6.0 > OK) before trying to run the code.
Option Explicit
Private Sub Experiment()
Dim placeName As String
placeName = "Delhi Airport, India"
Dim WebClient As MSXML2.ServerXMLHTTP60
Set WebClient = New MSXML2.ServerXMLHTTP60
With WebClient
.Open "POST", "https://www.latlong.net/_spm4.php", True
.setRequestHeader ":authority", "www.latlong.net"
.setRequestHeader ":method", "POST"
.setRequestHeader ":path", "/_spm4.php"
.setRequestHeader ":scheme", "https"
.setRequestHeader "accept", "*/*"
.setRequestHeader "content-type", "application/x-www-form-urlencoded"
.setRequestHeader "origin", "https://www.latlong.net"
.setRequestHeader "referer", "https://www.latlong.net/"
.setRequestHeader "user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36"
.setRequestHeader "x-requested-with", "XMLHttpRequest"
Dim bodyToSend As String
bodyToSend = "c1=" & Application.EncodeURL(placeName) & "&action=gpcm&cp="
.send bodyToSend
.waitForResponse
MsgBox ("Server's response to the request for Place Name '" & placeName & "' is " & _
vbNewLine & vbNewLine & .responseText)
End With
End Sub
You can access the server's response (which will contain the co-ordinates if the request was successful) with WebClient.responseText (or just .responseText inside the With statement) -- and then do what you need to with it.

Resources