First create a Translator resource in Microsoft's Azure portal (free tier for up to 2 mil characters per month) so that you can get your key and region that you'll use for STR_KEY and STR_REGION constants below.
Then you'll need to add mdJson.bas module to your project for JSON request/response handling.
Finally copy/paste these 35 lines of code in a standard BAS module:
Here is some sample code on how to setup and use Translator's API module above from some client code (change STR_KEY and STR_REGION as issued for your Translator resource in Azure):
cheers,
</wqw>
Then you'll need to add mdJson.bas module to your project for JSON request/response handling.
Finally copy/paste these 35 lines of code in a standard BAS module:
Code:
'--- mdTranslate.bas
Option Explicit
Private Const DEF_ENDPOINT As String = "https://api.cognitive.microsofttranslator.com"
Public Type UcsTranslateContext
Request As Object
End Type
Public Function TranslateInit(uCtx As UcsTranslateContext, sKey As String, sRegion As String, _
sFromLang As String, Optional ToLang As String = "en", Optional Endpoint As String)
Set uCtx.Request = CreateObject("WinHttp.WinHttpRequest.5.1")
With uCtx.Request
.Open "POST", IIf(LenB(Endpoint) <> 0, Endpoint, DEF_ENDPOINT) & "/translate?api-version=3.0&from=" & sFromLang & "&to=" & ToLang
.SetRequestHeader "Ocp-Apim-Subscription-Key", sKey
.SetRequestHeader "Ocp-Apim-Subscription-Region", sRegion
.SetRequestHeader "Content-Type", "application/json"
End With
End Function
Public Function TranslateText(uCtx As UcsTranslateContext, vTexts As Variant) As Variant
Dim sIndex As String
Dim oJson As Object
sIndex = IIf(IsArray(vTexts), "*", "0")
JsonValue(oJson, "$[" & sIndex & "].Text") = vTexts
With uCtx.Request
.Send JsonDump(oJson)
Set oJson = JsonParseObject(.ResponseText)
End With
If Not IsEmpty(JsonValue(oJson, "$.error")) Then
Err.Raise vbObjectError, , JsonValue(oJson, "$.error.message") & " (" & JsonValue(oJson, "$.error.code") & ")"
End If
TranslateText = JsonValue(oJson, "$[" & sIndex & "].translations[0].text")
End Function
Code:
'--- Form1.frm
Option Explicit
Private Const STR_KEY As String = "YOUR-KEY-HERE-2e8e45b3a14ebe76ab"
Private Const STR_REGION As String = "westeurope"
Private m_uLocalize As UcsTranslateContext
Private Sub Form_Load()
Dim vTexts As Variant
Dim vResult As Variant
'--- first setup API authentication and from/to languages
TranslateInit m_uLocalize, STR_KEY, STR_REGION, "bg", "en"
'--- then translate a single text
Debug.Print TranslateText(m_uLocalize, "Здравейте")
'--- keep on translating multiple texts at once on the same API session by passing an array of texts (up to 1000 entries)
vTexts = Array("Запис и изход", "Това е проба")
vResult = TranslateText(m_uLocalize, vTexts)
'--- result is array of translations
Debug.Print Join(vResult, vbCrLf)
End Sub
</wqw>