0

So I'm trying to use a VBA code that I found to define a function that uses Google Translate to translate a string from any given language to another. It works fine in most cases, but when the input is a language with special characters, (ex: Chinese or Arabic) it doesn't work. Below is the code I'm using:

Public Function Translate(strInput As String, strFromSourceLanguage As String, strToTargetLanguage As String) As String
    Dim strURL As String
    Dim objHTTP As Object
    Dim objHTML As Object
    Dim objDivs As Object, objDiv As Object
    Dim strTranslated As String

    ' send query to web page
    strURL = "https://translate.google.com/m?hl=" & strFromSourceLanguage & _
        "&sl=" & strFromSourceLanguage & _
        "&tl=" & strToTargetLanguage & _
        "&ie=UTF-8&prev=_m&q=" & strInput

    Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP") 'late binding
    objHTTP.Open "GET", strURL, False
    objHTTP.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
    objHTTP.send ""

    ' create an html document
    Set objHTML = CreateObject("htmlfile")
    With objHTML
        .Open
        .Write objHTTP.responsetext
        .Close
    End With
    
    'Range("H1") = objHTTP.responsetext
    
    Set objDivs = objHTML.getElementsByTagName("div")
    
    For Each objDiv In objDivs

        If objDiv.className = "result-container" Then
            strTranslated = objDiv.innerText
            Translate = strTranslated
        End If
        
    Next objDiv
    
    

    Set objHTML = Nothing
    Set objHTTP = Nothing

End Function

Also, here are some screenshots reflecting the situation:

Translate from Chinese to English

Translate from English to Chinese

Arturo
  • 11
  • 3

1 Answers1

0

Solved it guys!

As pointed out by @Noam Brand in Extract content of div from Google Translate with VBA, I simply used strInput = WorksheetFunction.EncodeURL(strInput) at the start of my code, so it codifies special characters before sending the query to Google Translate.

Arturo
  • 11
  • 3