VBA Direction API - Invalid Request Only through Code - vba

I'm from Brazil and sorry about my english but my error really driving me crazy!
I've already type a Code in VBA using this Directions API just for get the distance from A to B (in km).
Alright, I've talked to IT Security for allow my API Request and was permit and tested.
So today I set my macro to run perfectly and I discovered that my code return a INVALID_REQUEST, but more crazy about that is if I put the URL in the browser I get the response perfectly but when Excel try to run over coding, I get a INVALID_REQUEST from the XML return.
Look my code:
Function gglDirectionsResponse(ByVal strStartLocation, ByVal strEndLocation, ByRef strTravelTime, ByRef strDistance, ByRef strInstructions, Optional ByRef strError = "") As Boolean
On Error GoTo errorHandler
' Helper function to request and process XML generated by Google Maps.
Dim strURL As String
Dim objXMLHttp As Object
Dim objDOMDocument As Object
Dim nodeRoute As Object
Dim lngDistance As Long
Set objXMLHttp = CreateObject("MSXML2.XMLHTTP")
Set objDOMDocument = CreateObject("MSXML2.DOMDocument.6.0")
strStartLocation = Replace(strStartLocation, " ", "+")
strEndLocation = Replace(strEndLocation, " ", "+")
strURL = "https://maps.googleapis.com/maps/api/directions/xml" & _
"?origin=" & strStartLocation & _
"&destination=" & strEndLocation & _
"&key=MY_API_KEY" & _
"&sensor=false" & _
"&units=" & strUnits
'Send XML request
With objXMLHttp
.Open "GET", strURL, False
.setRequestHeader "Content-Type", "application/x-www-form-URLEncoded"
.send
objDOMDocument.LoadXML .responseText
End With
With objDOMDocument
If .SelectSingleNode("//status").Text = "OK" Then
'Get Distance
lngDistance = .SelectSingleNode("/DirectionsResponse/route/leg/distance/value").Text ' Retrieves distance in meters
Select Case strUnits
Case "imperial": strDistance = Round(lngDistance * 0.00062137, 1) 'Convert meters to miles
Case "metric": strDistance = Round(lngDistance / 1000, 1) 'Convert meters to miles
End Select
'Get Travel Time
strTravelTime = .SelectSingleNode("/DirectionsResponse/route/leg/duration/value").Text 'returns in seconds from google
strTravelTime = formatGoogleTime(strTravelTime) 'converts seconds to hh:mm
'Get Directions
For Each nodeRoute In .SelectSingleNode("//route/leg").ChildNodes
If nodeRoute.BaseName = "step" Then
strInstructions = strInstructions & nodeRoute.SelectSingleNode("html_instructions").Text & " - " & nodeRoute.SelectSingleNode("distance/text").Text & vbCrLf
End If
Next
strInstructions = CleanHTML(strInstructions) 'Removes MetaTag information from HTML result to convert to plain text.
Else
strError = .SelectSingleNode("//status").Text
GoTo errorHandler
End If
End With
gglDirectionsResponse = True
GoTo CleanExit
errorHandler:
If strError = "" Then strError = Err.Description
strDistance = -1
strTravelTime = "00:00"
strInstructions = ""
gglDirectionsResponse = False
CleanExit:
Set objDOMDocument = Nothing
Set objXMLHttp = Nothing
End Function
Function getGoogleDistance(ByVal strFrom, ByVal strTo) As String
'Returns the distance between strFrom and strTo
'where strFrom/To are address search terms recognisable by Google
'i.e. Postcode, address etc.
Dim strTravelTime As String
Dim strDistance As String
Dim strError As String
Dim strInstructions As String
If gglDirectionsResponse(strFrom, strTo, strTravelTime, strDistance, strInstructions, strError) Then
getGoogleDistance = strDistance
Else
getGoogleDistance = strError
End If
End Function
So, I just call the function gglDirectionsResponse sending, FROM and TO and the coding do the rest. As I said, I'd test and all works good, and now can't run. What I missing here guys?
The errorHandler is activate when the code try to run the specific line:
With objDOMDocument
If .SelectSingleNode("//status").Text = "OK" Then
Here return INVALID_REQUEST.
Look the URL after loaded:
https://maps.googleapis.com/maps/api/directions/xml?origin=Porto+Nacional-TO&destination=Silvanópolis-TO,+Brasil&key=MY_API_KEY&sensor=false&units=metric
Look the img from browser
browser img, from api url in the code
NOTE: I don't get macro or load or VBA code error, it's a errorHandler to validate the XML return, and the Return appear as invalid_request but browser load with success the same URL in the code.
Please please, somebody help me!

Try setting the request header to:
.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT enter code here5.0)"
Don't know if it will work though..

As I commented in the answer before. The problem was found when I wrote the line:
.SelectSingleNode("/").text
*Obviously after .Send command.
this return for me that I send a invalid parameter that contain a non-utf-8 character.
So the code in XML "/" it's like the root structure, and with this, I could get the error_message to understand more correctly the error.
So as I said, I'm from Brazil and our cities have a lot of (', í,á,é,ó ...) so I'd test and get finally the correct status.
And now my problem is how to convert any character, but easily if we compare :D

Related

VBA Outlook attachments post to URL

I have created a macro for outlook which opens up a userform, asks a few questions to select from, and then there's a submit button to send the message and the userform data to a POST url (our ticketing system). I am stuck on the last part of attachments. I can see the attachments list and loop through the attachment item objects, but I don't know which object call to make to send the actual file data to the POST form... all i can see is file size, file name, etc.
Any ideas where i would get the file contents and mime type for adding them to the URL post action as a form var?
Public senderaddress As String
Public thisEmailContent As String
Public thisEmailTEXT As String
Public thisStaffMember As Integer
Public emailAttachments As String
Sub MacroName()
thisStaffMember = 1
Set objItem = GetCurrentItem()
senderaddress = objItem.SenderEmailAddress
thisEmailContent = objItem.HTMLBody
thisEmailTEXT = objItem.Body
emailAttachments = objItem.Attachments
UserformName.Show
End Sub
Function GetCurrentItem() As Object
Dim objApp As Outlook.Application
Set objApp = Application
On Error Resume Next
Select Case TypeName(objApp.ActiveWindow)
Case "Explorer"
Set GetCurrentItem = _
objApp.ActiveExplorer.Selection.Item(1)
Case "Inspector"
Set GetCurrentItem = _
objApp.ActiveInspector.CurrentItem
Case Else
End Select
End Function
Then here's the last part of the Userform code where it actually sends the data to our ticket system when the Send Now button is clicked...
Public Function encodeURL(str As String)
Dim ScriptEngine As Object
Dim encoded As String
Set ScriptEngine = CreateObject("scriptcontrol")
ScriptEngine.Language = "JScript"
encoded = ScriptEngine.Run("encodeURIComponent", str)
encodeURL = encoded
End Function
Private Sub SendNow_Click()
Set sendReq = CreateObject("MSXML2.XMLHTTP")
With sendReq
.Open "POST", "https://ticketsystemurl.whatever/outlookinterface.php?action=openticket&fromEmail=" & encodeURL(senderaddress) & "&selectedCustomer=" & encodeURL(CustomerSelect.Value) & "&selectedContact=" & encodeURL(ContactSelect.Value), False
.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
.setRequestHeader "Content-type", "application/x-www-form-urlencoded"
.Send ("notifyCustomer=" & NotifyCustomer.Value & "&staffID=" & thisStaffMember & "&emailContent=" & encodeURL(thisEmailContent) & "&emailTEXT=" & encodeURL(thisEmailTEXT) & "&appendTicket=" & AppendToTicket.Value & "&createNewTicket=" & CreateNewTicket.Value & "&selectedTicket=" & encodeURL(SelectTicket.Value) & "&attachments=" & encodeURL(emailAttachments))
End With
Unload Me
End Sub
so far that submits everything except i cant figure out how to populate the post var "attachments" with the actual attachment filedata. Is this even possible?
Outlook would not do that for you. You will need to save the attachment as a file (Attachment.SaveAsFile), the read the contents of that file (Scripting.FileSystemObject object?) to use it in your web request.

Receiving 'Operation aborted error' when adding label to existing issue using jira api via vba even though label is successfully added

I'm trying to add a label to an existing issue in JIRA using the JIRA REST API via VBA. I can successfully login, get the session id/cookie, find the issue, and add a comment to the issue, but when I try to add a label I receive the following error message in Excel
However, the funny thing is the label is actually added
Before macro:
After macro:
I just can't explain or figure out what's going on. I've scoured the Internet (particularly the Atlassian forums) and have come across pages with examples that suggest I'm sending this request properly, but I still receive this Run-time error. Among many things here are a few things I've read/do to try and figure this out
I've done a GET on the issue's /editmeta to get the details for the labels field, which produced this
labels":{
"required":false,
"schema":{
"type":"array",
"items":"string",
"system":"labels"
},
"name":"Labels",
"autoCompleteUrl":"http://jira.company.local:8080/rest/api/1.0/labels/suggest?query=",
"operations":[
"add",
"set",
"remove"
]
}
So, according to that I should be able to use the "add" verb to add the label
The method I'm using (found at the bottom of this question) was adapted from user Patrick Patrick's comments from this thread
I've read the documentation on editing data from here
Learned that I should be using PUT instead of POST from here
Read specifically about how to update labels and followed the syntax from here, then tried the new method described in the response here
Finally, I found a bundle of bugs all related to this sort of issue floating around the Atlassian community. Branching out from here
So, that's where I'm at. My Question is simply this:
How can I add the label without receiving the Run-time error every time? It seems a bit pointless if my macro stops every time it adds one label to one issue
Below are the appropriate pieces of code that I am using.
JIRA Module:
Option Explicit
Sub JIRA()
Dim ASNumber As String, Supplier As String, IssueLink As String
Dim myJIRA As New clsJIRARest
With myJIRA
.UserName = "******"
.Password = "******"
.URL = "http://jira.company.local:8080"
If .Login = False Then Exit Sub
.GetLastSummary
IssueLink = .GetIssueLink '<-works fine
ASNumber = .GetASNumber '<-works fine
Supplier = .GetSupplierName '<-works fine
.PostExportComment '<-Throws run-time error 'Operation aborted'
.Logout
End With
End Sub
Appropriate parts of clsJIRARest Class Module:
Public Function Login() As Boolean
Login = False
With JiraAuth
.Open "POST", sURL & "/rest/auth/1/session", False
.setRequestHeader "Content-Type", "application/json"
.setRequestHeader "Accept", "application/json"
.send " {""username"" : """ & sJIRAUserID & """, ""password"" : """ & sJIRAPass & """}"" '*** HTTP-Request senden"
sErg = .responseText
If .Status = "200" Then
sCookie = "JSESSIONID=" & Mid(sErg, 42, 32) & "; Path=/" & sPfad
Login = True
End If
End With
End Function
Public Function GetLastSummary()
Dim myRegEx As Object: Set myRegEx = CreateObject("vbscript.regexp")
myRegEx.Global = True
myRegEx.Pattern = "as\/([0-9]{4,5}).+?(?=\-)" '<-Working
With JiraService
.Open "GET", sURL & "/rest/api/2/search?jql=assignee=mhill+order+by+lastViewed&now&maxResults=5", False
.setRequestHeader "Content-Type", "application/json"
.setRequestHeader "Accept", "application/json"
.setRequestHeader "Set-Cookie", sCookie '*** see Create a "Cookie"
.send
Set sRestAntwort = myRegEx.Execute(.responseText)
Sup = sRestAntwort(0)
ANum = sRestAntwort(0).Submatches(0)
myRegEx.Pattern = "self"":""(.+?(?=""))"
myRegEx.Global = False
Set sRestAntwort = myRegEx.Execute(.responseText)
sIssueLink = sRestAntwort(0).Submatches(0)
End With
End Function
'The comment posts fine below, but the label is what causes the error
Public Function PostExportComment() As Boolean
With JiraService
.Open "POST", sIssueLink & "/comment", False
.setRequestHeader "Content-Type", "application/json"
.setRequestHeader "Accept", "application/json"
.setRequestHeader "Set-Cookie", sCookie '*** see Create a "Cookie"
Dim sExportComment As String: sExportComment = "Full Export Requested - Awaiting Download Email"
.send " {""body"" : """ & sExportComment & """}"" '*** HTTP-Request senden"
'
' PostExportComment = IIf(.Status = "201", True, False)
.Open "PUT", sIssueLink, False
.setRequestHeader "Content-Type", "application/json"
.setRequestHeader "Accept", "application/json"
.setRequestHeader "Set-Cookie", sCookie '*** see Create a "Cookie"
Dim sExportingLabel As String: sExportingLabel = "Exporting"
'===============Errors on next line==================
.send " { ""update"": { ""labels"": [{""add"": """ & sExportingLabel & """}] } }"" '*** HTTP-Request senden" '(See below photo for error message)
Debug.Print .Status & "|" & .statusText
End With
End Function
It seems they're giving you a specific error code for this. That's great, because you can ignore that one and still handle other possible errors - and if that error number isn't specific to the "PostExportComment" action, then make yourself a local variable to track where the error is happening:
On Error GoTo ErrHandler
'...
currentStep = "PostExportComment"
.PostExportComment '<-Throws run-time error 'Operation aborted'
currentStep = "Logout"
.Logout
End With
CleanExit:
'clean up here
Exit Sub
ErrHandler:
'"Operation aborted" error is a false positive, see https://jira.atlassian.com/browse/JRA-27929
If currentStep = "PostExportComment" And Err.Number = -2147467260 Then
Resume Next
Else
'handle other possible runtime errors here
Resume CleanExit
End If
...or better, wrap the 3rd-party API in a class module and handle that error neatly in your own wrapper for PostExportComment:
Private wrapped As My3rdPartyThing
Public Enum MeaningfulError
ERR_FoobarNotInitialized = vbObjectError + 42
ERR_WrongCredentials
ERR_Whatever
End Enum
Private Sub Class_Initialize()
Set wrapped = New My3rdPartyThing
End Sub
Private Sub Class_Terminate()
Set wrapped = Nothing
End Sub
'wraps the "GetFoo" API method
Public Function GetFoo(ByVal bar As Long) As Something
On Error GoTo ErrHandler
Set GetFoo = wrapped.GetFoo(bar)
Exit Function
ErrHandler:
If Err.Number = 12345 Then
Err.Raise ERR_FoobarNotInitialized
Else
Err.Raise ERR_Whatever
End If
End Sub

url checker VBA, when redirected, show redirected url

I'm quite new to EXCEL VBA's and I'm kinda stuck finding a way to create a MACRO that shows whether a url is still active (200 ok),
or may be redirected, and if so, I want to know to what URL. And when it's not working at all, then return the right code with the reason the URL isn't working.
So at the moment I have a script that actually works but it doesn't return the url to which an url is redirected to.
It only returns (200 OK) when an url is still active, or the url that the original url has been redirected to is still active. So I know which URLs are dead or are redirected to a dead URL.
But I want to take it a step futher.
As the URLs that I want to check are in the "A" column at the moment, and the results return in the "B" column, I want to see the URL to which I've been redirected in the C column, everytime there an URL has been redirected.
I did find some functions online that should do the job but for some reason I can't fit them in my SUB. Like I mentioned before, it's all quite new to me.
This is what I have at the moment:
Sub CheckHyperlinks()
Dim oColumn As Range
Set oColumn = GetColumn() '' replace this with code to get the relevant column
Dim oCell As Range
For Each oCell In oColumn.Cells
If oCell.Hyperlinks.Count > 0 Then
Dim oHyperlink As Hyperlink
Set oHyperlink = oCell.Hyperlinks(1) '' I assume only 1 hyperlink per cell
Dim strResult As String
strResult = GetResult(oHyperlink.Address)
oCell.Offset(0, 1).Value = strResult
End If
Next oCell
End Sub
Private Function GetResult(ByVal strUrl As String) As String
On Error GoTo ErrorHandler
Dim oHttp As New MSXML2.ServerXMLHTTP30
oHttp.Open "HEAD", strUrl, False
oHttp.send
GetResult = oHttp.Status & " " & oHttp.statusText
Exit Function
ErrorHandler:
GetResult = "Error: " & Err.Description
End Function
I hope one of you could help me out.
Its better to use the WinHttp COM object. That will let you "disable" redirect handling. Read this forum post.
The component you need to reference is Microsoft WinHTTP Services.
Public Function GetResult(ByVal strUrl As String, Optional ByRef isRedirect As Boolean, Optional ByRef target As String) As String
Dim oHttp As New WinHttp.WinHttpRequest
oHttp.Option(WinHttpRequestOption_EnableRedirects) = False
oHttp.Open "HEAD", strUrl, False
oHttp.send
GetResult = oHttp.Status & " " & oHttp.statusText
If oHttp.Status = 301 Or oHttp.Status = 302 Then
isRedirect = True
target = oHttp.getResponseHeader("Location")
Else
isRedirect = False
target = Nothing
End If
End Function

SQL "%" equivalent in VBA

Is there any SQL equivalent of "%" sign in VBA?
I need to return a few files just with some characters in the middle.
Help really appreciated!
For instance here is my code: I need to download all file that has in the name 2013 from that webpage and save and call them differently. Is this mission possible?
Sub Sample()
Dim strURL As String
Dim strPath As String
Dim i As Integer
strURL = "http://cetatenie.just.ro/wp-content/uploads/Ordin-********.2013.pdf"
strPath = "C:\Documents and Settings\ee28118\Desktop\178.pdf"
Ret = URLDownloadToFile(0, strURL, strPath, 0, 0)
If Ret = 0 Then
MsgBox "File successfully downloaded"
Else
MsgBox "Unable to download the file"
End If
End Sub
You can use the Like Operator.
Characters in pattern Matches in string
? Any single character.
* Zero or more characters.
# Any single digit (0–9).
[charlist] Any single character in charlist.
[!charlist] Any single character not in charlist
Example :
Dim MyCheck
MyCheck = "aBBBa" Like "a*a" ' Returns True.
MyCheck = "F" Like "[A-Z]" ' Returns True.
MyCheck = "F" Like "[!A-Z]" ' Returns False.
MyCheck = "a2a" Like "a#a" ' Returns True.
MyCheck = "aM5b" Like "a[L-P]#[!c-e]" ' Returns True.
MyCheck = "BAT123khg" Like "B?T*" ' Returns True.
MyCheck = "CAT123khg" Like "B?T*" ' Returns False.
When you navigate to the uploads folder, you get a directory listing of all the files in it. You can loop through the hyperlinks on that listing and test each to see if it meets your criterion and, if so, download it. You need a reference to MSXML and MSHTML. Here's an example.
Sub Sample()
Dim sUrl As String
Dim xHttp As MSXML2.XMLHTTP
Dim hDoc As MSHTML.HTMLDocument
Dim hAnchor As MSHTML.HTMLAnchorElement
Dim Ret As Long
Dim sPath As String
Dim i As Long
sPath = "C:\Documents and Settings\ee28118\Desktop\"
sUrl = "http://cetatenie.just.ro/wp-content/uploads/"
'Get the directory listing
Set xHttp = New MSXML2.XMLHTTP
xHttp.Open "GET", sUrl
xHttp.send
'Wait for the page to load
Do Until xHttp.readyState = 4
DoEvents
Loop
'Put the page in an HTML document
Set hDoc = New MSHTML.HTMLDocument
hDoc.body.innerHTML = xHttp.responseText
'Loop through the hyperlinks on the directory listing
For i = 0 To hDoc.getElementsByTagName("a").Length - 1
Set hAnchor = hDoc.getElementsByTagName("a").Item(i)
'test the pathname to see if it matches your pattern
If hAnchor.pathname Like "Ordin-*.2013.pdf" Then
Ret = UrlDownloadToFile(0, sUrl & hAnchor.pathname, sPath, 0, 0)
If Ret = 0 Then
Debug.Print sUrl & hAnchor.pathname & " downloaded to " & sPath
Else
Debug.Print sUrl & hAnchor.pathname & " not downloaded"
End If
End If
Next i
End Sub
Edit
I assumed that URLDownloadToFile was already written. I didn't write one, I just used the below function to test the code that iterates through the files. You can use it to make sure the above code works for you, but you'll need to write the actual code to download the file eventually. With all the arguments to URLDownloadToFile, I'm surprised it doesn't exist already.
Function UrlDownloadToFile(lNum As Long, sUrl As String, sPath As String, lNum1 As Long, lNum2 As Long) As Long
UrlDownloadToFile = 0
End Function
Try below code : The boolean function would return true if the string has the string 2013 in it.
Sub Sample()
Dim result As Boolean
result = has2013("http://cetatenie.just.ro/wp-content/uploads/Ordin-********.2013.pdf")
Debug.Print result
result = has2013("http://cetatenie.just.ro/wp-content/uploads/Ordin-********.2014.pdf")
Debug.Print result
End Sub
Function has2013(lnk As String) As Boolean
has2013 = lnk Like "*2013*"
End Function
in VBA use the LIKE function with wildcard characters:
here is an example (copied from Ozgrid Forums)
Dim sht As Worksheet
For Each sht In ActiveWorkbook.Worksheets
If sht.Name Like "FRI*" Then
'Add code for Friday sheets
Else
If sht.Name Like "MON*" Then
'Add code for Monday sheets
End If
End If
Next
The multiplication character * takes the place of zero or more characters, whereas ? takes the place of exactly 1 character, and # takes the place of 1 number. There are other more specific char. matching strategies if you only want to match certain characters.
so there you go!
Also, you could take a look at Ozgrid Forums: Using Regular Expressions in VBA
To get a list of the files on the server, read up on FTP (using DIR) at Mr Excel - List files using FTP

Find the current user language

How can I tell the current user language in a vba program?
I need this to show a form in an appropriate language.
My initial code (utilising this vbforum code) assumed that Windows and Excel share a common language - likely but not bulletproof.
updated
The revised code:
Returns the Locale ID (LCID).
Looks up the LCID from this msft link.
Parses the LCID using a regexp to get the language.
Sample output on my machine below
The code will let the user know if there are any errors in accessing the LCID website, or in parsing the country name.
Sub GetXlLang()
Dim lngCode As Long
lngCode = Application.LanguageSettings.LanguageID(msoLanguageIDUI)
MsgBox "Code is: " & lngCode & vbNewLine & GetTxt(lngCode)
End Sub
Function GetTxt(ByVal lngCode) As String
Dim objXmlHTTP As Object
Dim objRegex As Object
Dim objRegMC As Object
Dim strResponse As String
Dim strSite As String
Set objXmlHTTP = CreateObject("MSXML2.XMLHTTP")
strSite = "http://msdn.microsoft.com/en-us/goglobal/bb964664"
On Error GoTo ErrHandler
With objXmlHTTP
.Open "GET", strSite, False
.Send
If .Status = 200 Then strResponse = .ResponseText
End With
On Error GoTo 0
strResponse = Replace(strResponse, "</td><td>", vbNullString)
Set objRegex = CreateObject("vbscript.regexp")
With objRegex
.Pattern = "><td>([a-zA-Z- ]+)[A-Fa-f0-9]{4}" & lngCode
If .Test(strResponse) Then
Set objRegMC = .Execute(strResponse)
GetTxt = objRegMC(0).submatches(0)
Else
GetTxt = "Value not found from " & strSite
End If
End With
Set objRegex = Nothing
Set objXmlHTTP = Nothing
Exit Function
ErrHandler:
If Not objXmlHTTP Is Nothing Then Set objXmlHTTP = Nothing
GetTxt = strSite & " unable to be accessed"
End Function
dim lang_code as long
lang_code = Application.LanguageSettings.LanguageID(msoLanguageIDUI)
This is another variation of the code posted by brettdj
Sub Test_GetLocale_UDF()
Dim lngCode As Long
lngCode = Application.LanguageSettings.LanguageID(msoLanguageIDUI)
MsgBox "Code Is: " & lngCode & vbNewLine & GetLocale(lngCode)
End Sub
Function GetLocale(ByVal lngCode) As String
Dim html As Object
Dim http As Object
Dim htmlTable As Object
Dim htmlRow As Object
Dim htmlCell As Object
Dim url As String
Set html = CreateObject("htmlfile")
Set http = CreateObject("MSXML2.XMLHTTP")
url = "https://www.science.co.il/language/Locale-codes.php"
On Error GoTo ErrHandler
With http
.Open "GET", url, False
.send
If .Status = 200 Then html.body.innerHTML = .responseText
End With
On Error GoTo 0
Set htmlTable = html.getElementsByTagName("table")(0)
For Each htmlRow In htmlTable.getElementsByTagName("tr")
For Each htmlCell In htmlRow.Children
If htmlCell.innerText = CStr(lngCode) Then
GetLocale = htmlRow.getElementsByTagName("td")(0).innerText
Exit For
End If
Next htmlCell
Next htmlRow
If GetLocale = "" Then GetLocale = "Value Not Found From " & url
Exit Function
ErrHandler:
If Not http Is Nothing Then Set http = Nothing
GetLocale = url & " Unable To Be Accessed"
End Function
Select Case Application.International(xlApplicationInternational.xlCountryCode)
Case 1: Call MsgBox("English")
Case 33: Call MsgBox("French")
Case 49: Call MsgBox("German")
Case 81: Call MsgBox("Japanese")
End Select
Straight out of here: https://bettersolutions.com/vba/macros/region-language.htm
Relevant Documentation: https://learn.microsoft.com/en-us/office/vba/api/excel.xlapplicationinternational
VBA Application.LanguageSettings.LanguageID(msoLanguageIDUI) gets only Microsoft Office Access or Microsoft Excel User interface Language. But does not reflect the Windows System display language used for Windows Display, every thing as MsgBox() buttons etc.
If user changes his Windows Display language via Windows Control Panel, this Application level setting will not change. In which case, we can use this Kernel dll function to get the new LCID (Microsoft Language Code IDentifier, 1036=French, 1033=English, ...), with this code in a VBA Module:
Private Declare Function GetUserDefaultUILanguage Lib "kernel32.dll" () As Long
Public Function winGetUserDefaultUILanguage()
winGetUserDefaultUILanguage = GetUserDefaultUILanguage()
End Function
Then you can call the public function winGetUserDefaultUILanguage() every where in your VBA code to get Windows LCID.
The kernel dll function GetUserDefaultUILanguage() will reflect the changement via Windows Display Language ID.
For example, as I've French Windows display language, LCID=1036, my Office is also in French (LCID=1036),
VBA Debugger Console:
Now we switch to English Windows display language via Control Panel (LCID=1033 for English), but my Office language ID remains unchanged (LCID=1036):
VBA Debugger Console:
From LCID, you can further get Language Tag, Language Name from Microsoft API documents here or here.