VBA 语言翻译器 UDF 无法处理特殊字符

VBA language translator UDF not working with special characters

所以我尝试使用我发现的 VBA 代码来定义一个函数,该函数使用 Google Translate 将字符串从任何给定语言翻译成另一种语言。它在大多数情况下工作正常,但当输入是一种具有特殊字符的语言时(例如:中文或阿拉伯语)它不起作用。下面是我正在使用的代码:

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

此外,这里有一些反映情况的屏幕截图:

Translate from Chinese to English

Translate from English to Chinese

伙计们解决了!

正如@Noam Brand 在 Extract content of div from Google Translate with VBA 中指出的那样,我只是在代码的开头使用了 strInput = WorksheetFunction.EncodeURL(strInput),因此它会在将查询发送到 Google 之前对特殊字符进行编码.