Option Explicit
Public Function Translate2(Optional SendText As String, Optional From As String = "en", Optional ToLang As String = "fr", Optional Convert = 0)
Dim RQ As Object, URL$, elem As Object, X&
Set RQ = CreateObject("microsoft.xmlhttp") '"MSXML2.ServerXMLHTTP"
If Convert <> 0 Then If Convert = 1 Then SendText = EncodeText1(SendText) Else SendText = EncodeText2(SendText)
URL = "https://translate.google.pl/m?hl=" & From & "&sl=" & From & "&tl=" & ToLang & "&ie=UTF-8&prev=_m&q=" & SendText
RQ.Open "POST", URL, False
RQ.SetRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
RQ.send
With CreateObject("htmlfile")
.body.innerhtml = RQ.responsetext
For Each elem In .ALL
If elem.Tagname = "DIV" And elem.classname = "t0" Then Translate2 = elem.innerhtml: Exit For
Next
End With
End Function
'---------------------------------------------------------------------------------------------------------
Function EncodeText1(chaine) As String
Dim t1, t2, i&
t1 = "âÄàéèéèêëiîôùûü": t2 = "aAaeeeeeeiIoouuu"
For i = 1 To Len(t1): chaine = Replace(chaine, Mid(t1, i, 1), Mid(t2, i, 1)): Next
EncodeText1 = chaine
End Function
'---------------------------------------------------------------------------------------------------------
Function EncodeText2(chaine) As String 'sur la base Dranreb exceldownload
Dim chaine2$, P&, C$, A&
chaine2 = Replace(chaine, "'", "%27")
For P = 1 To Len(chaine)
C = Mid$(chaine, P, 1): A = AscW(C)
If A > 127 Then chaine2 = Replace(chaine2, C, "\u" & Right$("000" & LCase$(Hex$(A)), 4))
Next
EncodeText2 = chaine2
End Function
'---------------------------------------------------------------------------------------------------------
Function DecodeText2(ByVal Txt As String) As String 'sur la base Dranreb exceldownload
Dim TJn() As String, J As Long
TJn = Split(Txt, "\u")
DecodeText2 = Replace(Txt, "%27", "'")
For J = 1 To UBound(TJn):
DecodeText2 = Replace(DecodeText2, "\u" & Left$(TJn(J), 4), ChrW$(Val("&H" & Left$(TJn(J), 4))))
Next J
End Function
'---------------------------------------------------------------------------------------------------------
Sub test()
'utilisation sequencée
MsgBox Translate2(EncodeText1("Les élèves vont à l'école."), "fr", "en") & vbCrLf & _
Translate2(EncodeText2("Les élèves vont à l'école."), "fr", "en")
'utilisation compact vba et formule
MsgBox Translate2("Les élèves vont à l'école.", "fr", "en", 1)
MsgBox Translate2("Les élèves vont à l'école.", "fr", "en", 2)
'************************************************************
'formule BASE *
'=Translate(A1;"fr";"en";2)'conversion hexa *
'=Translate(A1;"fr";"en";1)'conversion by replacements *
'************************************************************
End Sub