Excel VBA宏定义自定义方法使用谷歌翻译对单元格进行翻译

打开excel
方法一:台式电脑按快捷键Alt+F11,笔记本用FN+Alt+F11

方法二:单击视图->宏

Public Function GglTranslate(strInput As String, FrmLng As String, ToLng 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.cn/m?hl=" & FrmLng & _

    strURL = "https://translate.google.cn/m?hl=zh-CN" & _
        "&sl=" & FrmLng & _
        "&tl=" & ToLng & _
        "&ie=UTF-8&prev=_m&q=" & strInput

    Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP") 'late binding
    objHTTP.Open "GET", strURL, False
    objHTTP.setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36"
    objHTTP.send ""
    ' create an html document
    Set objHTML = CreateObject("htmlfile")
    With objHTML
        .Open
        .Write objHTTP.responseText
        .Close
    End With
    
    Set objDivs = objHTML.getElementsByTagName("div")
  
    For Each objDiv In objDivs

        If objDiv.className = "result-container" Then
            strTranslated = objDiv.innerText
            If strTranslated <> "" Then GglTranslate = strTranslated
          
        End If
        
    Next objDiv
    
    

    Set objHTML = Nothing
    Set objHTTP = Nothing

End Function

使用方法对单元格F2、H2、I2进行合并翻译

=GglTranslate(F2&"."&H2&"."&I2,"en","zh-CN") 
posted @ 2021-06-10 10:01  叨叨勋  阅读(1591)  评论(3编辑  收藏  举报