5年多來,我已經使用此代碼在Excel VBA宏中將用戶輸入的英文文本轉換爲法語或德語。這是微軟Azure Marketplace,因爲我的使用很少,所以它是免費的。在令人驚歎的VBA宏中使用Azure翻譯器
Function MicrosoftTranslate(sText As String, Optional sLanguageFrom As String = "", Optional sLanguageTo As String = "en") As String
Dim sRequest As String, sResponseText As String
sRequest = "Translate?from=" & sLanguageFrom & "&to=" & sLanguageTo & "&text=" & sText
sResponseText = MSHttpRequest(sRequest)
'Debug.Print sResponseText
MicrosoftTranslate = StringFromXML(sResponseText)
End Function
Function MicrosoftTranslatorDetect(sText As String) As String
' returns lowercase two character code eg "fr"
MicrosoftTranslatorDetect = StringFromXML(MSHttpRequest("Detect?text=" & sText))
End Function
Function MSHttpRequest(sRequest As String) As String
Dim sURL As String, oH As Object, sToken As String
sURL = "http://api.microsofttranslator.com/V2/Http.svc/" & sRequest
sToken = GetAccessToken()
Set oH = CreateObject("MSXML2.XMLHTTP")
oH.Open "GET", sURL, False
oH.setRequestHeader "Authorization", "Bearer " & sToken
oH.send
MSHttpRequest = oH.responseText
Set oH = Nothing
End Function
Function GetAccessToken() As String
Static sAccess_Token As String, dtExpiry_Time As Date
Const OAUTH_URI As String = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13"
'get Your Client ID and client secret from
'https://datamarket.azure.com/developer/applications
Const CLIENT_ID As String = "xxxxxxxxx"
Const CLIENT_SECRET As String = "1234567890abcdefghijklmnopqrstuvwxyz"
Dim sRequest As String, sResponse As String
Dim webRequest As Object
If Now() > dtExpiry_Time Then ' time for a new access token
Set webRequest = CreateObject("MSXML2.XMLHTTP")
sRequest = "grant_type=client_credentials" & _
"&client_id=" & CLIENT_ID & _
"&client_secret=" & URLEncode(CLIENT_SECRET) & _
"&scope=http://api.microsofttranslator.com"
webRequest.Open "POST", OAUTH_URI, False
webRequest.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
webRequest.send (sRequest)
sResponse = webRequest.responseText
Set webRequest = Nothing
If InStr(1, sResponse, """error:""", vbTextCompare) > 0 Then
Err.Raise 9999, "GetAccessToken " & sResponse
End If
sAccess_Token = NameValue("access_token", sResponse)
dtExpiry_Time = Now() + Val(NameValue("expires_in", sResponse))/60/60/24 ' maybe *.95 for safety margin
'Debug.Print "Token expires at "; Format$(dtExpiry_Time, "hh:mm:ss")
End If
GetAccessToken = sAccess_Token
End Function
現在,隨着新的微軟Azure,我的搭便車似乎已經結束了。所以現在我需要轉換我的VBA代碼。我看了,還沒有找到一個很好的參考,這將有助於轉換附加的例程。我在VBA方面並不差,但需要幫助實現這些新功能。
有人可以幫助或指向我的一些參考(像我這樣的新手),這將使我與新系統。
在我運行某些東西之後,我可以決定這個小應用程序是否值得我的錢。
感謝..... RDK
好的,我會給它看看。我現在正在旅行,所以它將不得不等待。謝謝.... RDK – RDK
好的,我已經爲Azure認知服務(文本翻譯器)註冊了一個「即付即用」帳戶。我有一個帳戶名稱,資源組名稱和一對鑰匙。但是我還沒有找到關於如何在我的上述應用程序中使用這些代碼的示例代碼。看起來,我獨自一人在試圖用VBA使用它的荒野?一些具體的幫助,參考或例子將不勝感激。 – RDK
我剛剛發現這個參考(https://sysmod.wordpress.com/2017/01/20/vba-code-for-microsoft-text-translator-api/)。我正在通過它。如果回答我的問題,我會回覆。 – RDK