Public Function translate(textToBeTranslated As String, resultLanguageCode As String, Optional sourceLanguageCode As String = “”) As String
‘Translates given text with Google Translate
‘Supported languages can be found here: http://code.google.com/intl/fi-FI/apis/ajaxlanguage/documentation/#SupportedLanguages
‘If source language is omitted, Google Translate tries to detect it automatically
‘
‘Function created by Mikael Thuneberg. Code for non-ASCII character encoding picked from a procedure by alexspi (http://www.experts-exchange.com/M_4420197.html)
Dim objhttp As Object
Dim URL As String
Dim i As Integer
Dim iAsc As Long
Dim sAsc As String
Dim sTemp As String
Dim objStream As Object
Dim data() As Byte
Dim ByteArrayToEncode() As Byte
Set objStream = CreateObject(“ADODB.Stream”)
objStream.Charset = “utf-8″
objStream.Mode = 3
objStream.Type = 2
objStream.Open
objStream.WriteText textToBeTranslated
objStream.Flush
objStream.Position = 0
objStream.Type = 1
objStream.Read 3
data = objStream.Read()
objStream.Close
ByteArrayToEncode = data
textToBeTranslated = “”
For i = 0 To UBound(ByteArrayToEncode)
iAsc = ByteArrayToEncode(i)
Select Case iAsc
Case 32 ‘space
sTemp = “+”
Case 48 To 57, 65 To 90, 97 To 122
sTemp = Chr(ByteArrayToEncode(i))
Case Else
Debug.Print iAsc
sTemp = “%” & Hex(iAsc)
End Select
textToBeTranslated = textToBeTranslated & sTemp
Next
Set objhttp = CreateObject(“MSXML2.ServerXMLHTTP”)
URL = “http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=” & textToBeTranslated & “&langpair=” & sourceLanguageCode & “%7C” & resultLanguageCode
objhttp.Open “GET”, URL, False
objhttp.setTimeouts 1000000, 1000000, 1000000, 1000000
objhttp.send (“”)
translate = objhttp.responseText
translate = Right(translate, Len(translate) – InStr(1, translate, “translatedText”) – 16)
translate = Left(Left(translate, InStr(1, translate, Chr(34)) – 1), 255)
translate = Replace(translate, “quot;”, Chr(39))
If translate = ” null, ” Then translate = “Language not found”
End Function
