Translate text using vba

后端 未结 5 1172
既然无缘
既然无缘 2020-11-29 07:08

Probably could be a rare petition, but here is the issue.

I am adapting an excel of a third-party to my organization. The excel is developed in English and the peop

5条回答
  •  不知归路
    2020-11-29 07:24

    This is how I would do it. It's function with optional enumeration objects that point to language codes used by google translate. For simplicity I only included a few language codes. Also, in this sample I selected the Microsoft Internet Controls reference so instead of creating an object, there's an InternetExplorer object used. And finally, to get rid of having to clean up the output, I just used .innerText rather than .innerHTML. Keep in mind, there's a character limit of around 3000 or so with google translate, and also, you must set IE=nothing especially if you will be using this multiple times, otherwise you will create multiple IE processes and eventually it won't work anymore.

    Setup...

    Option Explicit
    
    Const langCode = ("auto,en,fr,es")
    
    Public Enum LanguageCode
        InputAuto = 0
        InputEnglish = 1
        InputFrench = 2
        InputSpanish = 3
    End Enum
    
    Public Enum LanguageCode2
        ReturnEnglish = 1
        ReturnFrench = 2
        ReturnSpanish = 3
    End Enum
    

    Test...

    Sub Test()
    
    Dim msg As String
    
    msg = "Hello World!"
    
    MsgBox AutoTranslate(msg, InputEnglish, ReturnSpanish)
    
    End Sub
    

    Function...

    Public Function AutoTranslate(ByVal Text As String, Optional LanguageFrom As LanguageCode, Optional LanguageTo As LanguageCode2) As String
    
    Dim langFrom As String, langTo As String, IE As InternetExplorer, URL As String, myArray
    
    If IsMissing(LanguageFrom) Then
        LanguageFrom = InputAuto
    End If
    If IsMissing(LanguageTo) Then
        LanguageTo = ReturnEnglish
    End If
    
    myArray = Split(langCode, ",")
    langFrom = myArray(LanguageFrom)
    langTo = myArray(LanguageTo)
    
    URL = "https://translate.google.com/#" & langFrom & "/" & langTo & "/" & Text
    
    Set IE = New InternetExplorer
    
    IE.Visible = False
    IE.Navigate URL
    
        Do Until IE.ReadyState = 4
            DoEvents
        Loop
    
        Application.Wait (Now + TimeValue("0:00:5"))
    
        Do Until IE.ReadyState = 4
            DoEvents
        Loop
    
        AutoTranslate = IE.Document.getElementByID("result_box").innerText
    
        IE.Quit
    
        Set IE = Nothing
    
    
    End Function
    

提交回复
热议问题