在Excel VBA宏中使用Google翻译

时间:2015-04-09 07:13:54

标签: excel vba

民众......多年来,我在我的一个Excel宏中使用了以下功能来帮助我将照片标题从英文拼成法文。这个AM它开始抛出一个错误,它指向下面代码中的.Send命令:

Public Function getGoogleTranslation(strSource As String, strSourceLang As String, strDestLang As String) As String
Dim strURL As String, x As String

strURL = "http://translate.google.com/translate_a/t?client=t&text=" & _
         Replace(strSource, " ", "%20") & _
         "&hl=en&sl=" & strSourceLang & _
         "&tl=" & strDestLang & "&multires=1&pc=0&rom=1&sc=1"

With CreateObject("msxml2.xmlhttp")
    .Open "get", strURL, False
    .send
    x = .responseText
End With

getGoogleTranslation = Replace(Replace(Split(x, ",")(0), "[", ""), """", "")

End Function

当我将strURL的内容直接复制/粘贴到IE中时,我第一次收到CAPTCHA和评论他们正在检查“机器人”。第二次直接工作。他们必须设置一个cookie?

这周围有吗?或者另一种方法来获取在宏中翻译的简单短语?

感谢.... RDK

2 个答案:

答案 0 :(得分:0)

以下是vba的谷歌翻译模块的beta实现: (用它来快速翻译软件)...... 也许您需要在事后检查文本是否正确。

Private Function GoogleTranslate(ByVal Text4Translation, ByVal resLang, ByVal srcLang) As String
Dim IEApp As Object
Dim IEDoc As Object
Dim IEUrl As String
Dim IESrc As String
Dim IEBeg As Long
Dim IEEnd As Long
' Neues Browser Objekt erzeugen
Set IEApp = CreateObject("InternetExplorer.Application")
' Browser versteckt ausführen (höhere Geschwindigkeit)
'IEApp.Visible = False
' URL Generieren
Text4Translation = Replace(Text4Translation, " ", "%20")
IEUrl = "https://translate.google.com/#" & srcLang & "/" & resLang & "/" & Text4Translation
' HTML-Datei aufrufen
IEApp.navigate IEUrl
Do
    Application.Wait Now + TimeSerial(0, 0, 1)
Loop Until IEApp.busy = False
Set IEDoc = IEApp.document
' Quelltext einlesen
IESrc = IEDoc.body.innerHTML
' Bereich auslesen
IEBeg = InStr(1, IESrc, "result_box")
If IEBeg = 0 Then
    IESrc = " # Nothing found"
Else
    IEEnd = InStr(IEBeg, IESrc, "</div")
    IESrc = Mid(IESrc, IEBeg + 40, IEEnd - IEBeg - 40)
    IESrc = Replace(IESrc, "<span class=" & Chr(34) & "hps" & Chr(34) & ">", "")
    IESrc = Replace(IESrc, "<span class=" & Chr(34) & "atn" & Chr(34) & ">", "")
    IESrc = Replace(IESrc, "<span class=" & Chr(34) & "hps atn" & Chr(34) & ">", "")
    IESrc = Replace(IESrc, "<span>", "")
    IESrc = Replace(IESrc, "</span>", "")
    If IESrc = "" Then IESrc = " # Instr-Error"
End If
Set IEApp = Nothing
GoogleTranslate = IESrc
End Function

resLang =&#34; de&#34;,&#34; en&#34;,...(TargetLanguage)

srcLang =&#34; de&#34;,&#34; en&#34;,...(SourceLanguage)

(注意,它只是一种解决方法!)

答案 1 :(得分:0)

请参阅获取Google成绩单的拼音(作为字符串) (当使用一个单词从英语翻译时,它正好在TextBox下面)