You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Word VBA中获取谷歌翻译的独立返回值?

在Word VBA中实现谷歌翻译的独立返回值方案

谷歌翻译没有为Word VBA提供原生的内置返回值接口,但可以通过调用谷歌翻译的REST API实现独立于Excel环境的文本翻译,直接返回翻译结果到Word文档中。以下是可直接使用的VBA代码示例:

Sub GoogleTranslateInWord()
    Dim apiKey As String
    Dim sourceLang As String
    Dim targetLang As String
    Dim inputText As String
    Dim url As String
    Dim xmlHttp As Object
    Dim response As String
    Dim parsedResult As String
    
    ' 替换为你的谷歌翻译API密钥
    apiKey = "YOUR_API_KEY"
    sourceLang = "zh-CN" ' 源语言,可按需修改
    targetLang = "en" ' 目标语言,可按需修改
    
    ' 获取Word中选中的文本
    If Selection.Type = wdSelectionNormal Then
        inputText = Selection.Text
    Else
        MsgBox "请先选中要翻译的文本"
        Exit Sub
    End If
    
    ' 构造API请求URL
    url = "https://translation.googleapis.com/language/translate/v2?key=" & apiKey & _
          "&q=" & URLEncode(inputText) & _
          "&source=" & sourceLang & _
          "&target=" & targetLang
    
    ' 发送HTTP请求
    Set xmlHttp = CreateObject("MSXML2.XMLHTTP")
    xmlHttp.Open "GET", url, False
    xmlHttp.Send
    
    ' 解析返回的JSON结果
    response = xmlHttp.ResponseText
    parsedResult = Split(Split(response, """translatedText"":""")(1), """")(0)
    
    ' 将翻译结果插入到选中文本之后
    Selection.Collapse Direction:=wdCollapseEnd
    Selection.TypeText vbCrLf & "翻译结果:" & parsedResult
    
    Set xmlHttp = Nothing
End Sub

' 辅助函数:URL编码
Function URLEncode(text As String) As String
    Dim charCode As Integer
    Dim i As Integer
    URLEncode = ""
    For i = 1 To Len(text)
        charCode = Asc(Mid(text, i, 1))
        Select Case charCode
            Case 48 To 57, 65 To 90, 97 To 122
                URLEncode = URLEncode & Mid(text, i, 1)
            Case Else
                URLEncode = URLEncode & "%" & Hex(charCode)
        End Select
    Next i
End Function

使用说明

  • 你需要先在谷歌云平台申请翻译API密钥,并确保账户有可用额度。
  • 代码中sourceLang和targetLang可根据需求修改语言代码(比如"en"转"zh-CN")。
  • 运行宏前选中要翻译的文本,宏会在选中内容后插入翻译结果。

如果不想依赖API密钥,也可以通过模拟网页请求的方式调用谷歌翻译网页版,但这种方式不稳定,谷歌可能会限制请求,且需要处理更复杂的HTML解析,不推荐长期使用。

内容的提问来源于stack exchange,提问作者Roy1953

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 00:22:34