I have found a link at SO that may make difference at this query
Upload a Picture to file.io (HTTP Post) in VBA
The code from this link
Sub UploadFilesUsingVBAORIGINAL()
'this proc will upload below files to https://file.io/
' png, jpg, txt
Dim fileFullPath As String
fileFullPath = ThisWorkbook.Path & "\Sample.txt"
POST_multipart_form_dataO fileFullPath
End Sub
Private Function GetGUID() As String
' Generate uuid version 4 using VBA
GetGUID = WorksheetFunction.Concat(WorksheetFunction.Dec2Hex(WorksheetFunction.RandBetween(0, 4294967295#), 8), "-", WorksheetFunction.Dec2Hex(WorksheetFunction.RandBetween(0, 65535), 4), "-", WorksheetFunction.Dec2Hex(WorksheetFunction.RandBetween(16384, 20479), 4), "-", WorksheetFunction.Dec2Hex(WorksheetFunction.RandBetween(32768, 49151), 4), "-", WorksheetFunction.Dec2Hex(WorksheetFunction.RandBetween(0, 65535), 4), WorksheetFunction.Dec2Hex(WorksheetFunction.RandBetween(0, 4294967295#), 8))
End Function
Private Function GetFileSize(fileFullPath As String) As Long
Dim lngFSize As Long, lngDSize As Long
Dim oFO As Object, OFS As Object
lngFSize = 0
Set OFS = CreateObject("Scripting.FileSystemObject")
If OFS.FileExists(fileFullPath) Then
Set oFO = OFS.GetFile(fileFullPath)
GetFileSize = oFO.Size
Else
GetFileSize = 0
End If
Set oFO = Nothing
Set OFS = Nothing
End Function
Private Function ReadBinary(strFilePath As String)
Dim ado As Object, bytFile
Set ado = CreateObject("ADODB.Stream")
ado.Type = 1
ado.Open
ado.LoadFromFile strFilePath
bytFile = ado.Read
ado.Close
ReadBinary = bytFile
Set ado = Nothing
End Function
Private Function toArray(str)
Dim ado As Object
Set ado = CreateObject("ADODB.Stream")
ado.Type = 2
ado.Charset = "_autodetect"
ado.Open
ado.WriteText (str)
ado.Position = 0
ado.Type = 1
toArray = ado.Read()
Set ado = Nothing
End Function
Sub POST_multipart_form_dataO(filePath As String)
Dim oFields As Object, ado As Object
Dim sBoundary As String, sPayLoad As String, GUID As String
Dim fileType As String, fileExtn As String, fileName As String
Dim sName As Variant
fileName = Right(filePath, Len(filePath) - InStrRev(filePath, "\"))
fileExtn = Right(filePath, Len(fileName) - InStrRev(fileName, "."))
Select Case fileExtn
Case "png"
fileType = "image/png"
Case "jpg"
fileType = "image/jpeg"
Case "txt"
fileType = "text/plain"
End Select
Set oFields = CreateObject("Scripting.Dictionary")
With oFields
.Add "qquuid", LCase(GetGUID)
.Add "qqtotalfilesize", GetFileSize(filePath)
End With
sBoundary = String(27, "-") & "7e234f1f1d0654"
sPayLoad = ""
For Each sName In oFields
sPayLoad = sPayLoad & "--" & sBoundary & vbCrLf
sPayLoad = sPayLoad & "Content-Disposition: form-data; name=""" & sName & """" & vbCrLf & vbCrLf
sPayLoad = sPayLoad & oFields(sName) & vbCrLf
Next
sPayLoad = sPayLoad & "--" & sBoundary & vbCrLf
sPayLoad = sPayLoad & "Content-Disposition: form-data; name=""file""; " & "filename=""" & fileName & """" & vbCrLf
sPayLoad = sPayLoad & "Content-Type: " & fileType & vbCrLf & vbCrLf & vbCrLf & vbCrLf & vbCrLf
sPayLoad = sPayLoad & "--" & sBoundary & "--"
Set ado = CreateObject("ADODB.Stream")
ado.Type = 1
ado.Open
ado.Write toArray(sPayLoad)
ado.Write ReadBinary(filePath)
ado.Position = 0
With CreateObject("MSXML2.ServerXMLHTTP")
.Open "POST", "https://file.io", False
.setRequestHeader "Content-Type", "multipart/form-data; boundary=" & sBoundary
.send (ado.Read())
Debug.Print .responseText
End With
End Sub
Anyone can try this code as the website is for free. When I run the code, I got "Success" in the immediate window and got a link to the uploaded file.
This appears to have no problem but when taking the link and put it in a browser, I got 404 Page not found
I tried uploading the same file manually and it works well without any problem as for the link I got from this manual steps
Any help please?
Posted here too
https://chandoo.org/forum/threads/upload-file-to-file-io-using-post-method.43925/
It looks to me like the final boundary is in the wrong place ie before the file content. Try
Sub UploadToIO()
Const PATH = "c:\tmp\"
Const FILENAME = "testimage.png"
Const CONTENT = "image/png"
Const URL = "https://file.io"
' generate boundary
Dim BOUNDARY, s As String, n As Integer
For n = 1 To 16: s = s & Chr(65 + Int(Rnd * 25)): Next
BOUNDARY = s & CDbl(Now)
Dim part As String, ado As Object
part = "--" & BOUNDARY & vbCrLf
part = part & "Content-Disposition: form-data; name=""file""; filename=""" & FILENAME & """" & vbCrLf
part = part & "Content-Type: " & CONTENT & vbCrLf & vbCrLf
' read file into image
Dim image
Set ado = CreateObject("ADODB.Stream")
ado.Type = 1 'binary
ado.Open
ado.LoadFromFile PATH & FILENAME
ado.Position = 0
image = ado.read
ado.Close
' combine part, image , end
ado.Open
ado.Position = 0
ado.Type = 1 ' binary
ado.Write ToBytes(part)
ado.Write image
ado.Write ToBytes(vbCrLf & "--" & BOUNDARY & "--")
ado.Position = 0
'ado.savetofile "c:\tmp\debug.bin", 2 ' overwrite
' send request
With CreateObject("MSXML2.ServerXMLHTTP")
.Open "POST", URL, False
.setRequestHeader "Content-Type", "multipart/form-data; boundary=" & BOUNDARY
.send ado.read
Debug.Print .responseText
End With
MsgBox "File: " & PATH & FILENAME & vbCrLf & _
"Boundary: " & BOUNDARY, vbInformation, "Uploaded to " & URL
End Sub
Function ToBytes(str As String) As Variant
Dim ado As Object
Set ado = CreateObject("ADODB.Stream")
ado.Open
ado.Type = 2 ' text
ado.Charset = "_autodetect"
ado.WriteText str
ado.Position = 0
ado.Type = 1
ToBytes = ado.read
ado.Close
End Function
Related
Need to split the 3rd row and have it in the below xml format.
My Excel data:
ID
EMail
UserGroupID
Aravind
Aravind#gmail.com
Sports(12-34)
Aravind2
Aravind2#gmail.com
Sports(3-24-5),Health(5-675-85), Education(57-85-96)
My XML data:
<?xml version="1.0" encoding="utf-8"?>
<Core-data ContextID="Context1" WorkspaceID="Main">
<UserList>
<User ID="Aravind" ForceAuthentication="false" Password="1234" EMail="Aravind#gmail.com">
<Name>Aravind</Name>
<UserGroupLink UserGroupID="12-34"/>
</User>
<User ID="Aravind2" ForceAuthentication="false" Password="1234" EMail="Aravind#gmail.com">
<Name>Aravind2</Name>
<UserGroupLink UserGroupID="3-24-5"/>
<UserGroupLink UserGroupID="5-675-85"/>
<UserGroupLink UserGroupID="57-85-96"/>
</User>
</UserList>
</Core-data>
The code Im using:(Need change in delimiting the 3 rd row & location only)
Sub Generate_xml()
Const FOLDER = "C:\Temp\"
Const XLS_FILE = "UserDataEntry.xlsm"
Const XML_FILE = "User XML.xml"
Const XML = "<?xml version=""1.0"" encoding=""utf-8""?>" & vbCrLf & _
"<Core-data ContextID=""Context1"" WorkspaceID=""Main"">" & vbCrLf & _
" <UserList>" & vbCrLf
Dim wb As Workbook, ws As Worksheet, ar, s As String
Dim iLastRow As Long, r As Long, n As Integer
' open source workbook
Set wb = Workbooks.Open(FOLDER & XLS_FILE, 1, 1)
Set ws = wb.Sheets("Sheet1")
iLastRow = ws.Cells(Rows.Count, "A").End(xlUp).Row
' create XML document
'<User ID="Aravind" ForceAuthentication="false" Password="1234" EMail="Aravind#gmail.com.com">
' <Name>Aravind</Name>
' <UserGroupLink UserGroupID="Sports"/>
'</User>
s = XML
For r = 2 To iLastRow
s = s & " <User ID=""" & ws.Cells(r, 1) & """" & _
" ForceAuthentication=""false"" Password=""1234""" & _
" EMail=""" & ws.Cells(r, 2) & """>" & vbCrLf
s = s & " <Name>" & ws.Cells(r, 1) & "</Name>" & vbCrLf
ar = Split(ws.Cells(r, 3), ",")
For n = LBound(ar) To UBound(ar)
s = s & " <UserGroupLink UserGroupID=""" & Trim(ar(n)) & """/>" & vbCrLf
Next
s = s & " </User>" & vbCrLf
Next
s = s & " </UserList>" & vbCrLf & "</Core-data>"
' save
Dim fso, ts
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.createtextfile(FOLDER & XML_FILE)
ts.write s
ts.Close
MsgBox "Xml created to " & FOLDER & XML_FILE
End Sub
Is there is any way to run this VBA code in any location and the XML generated to be in same location.
Kindly share your inputs & thanks in advance.
Try something like this:
Sub Generate_xml()
Const FOLDER = "C:\Temp\"
Const XLS_FILE = "UserDataEntry.xlsm"
Const XML_FILE = "User XML.xml"
Const XML = "<?xml version=""1.0"" encoding=""utf-8""?>" & vbCrLf & _
"<Core-data ContextID=""Context1"" WorkspaceID=""Main"">" & vbCrLf & _
" <UserList>" & vbCrLf
Dim wb As Workbook, ws As Worksheet, s As String, savePath As String
Dim r As Long, e
' open source workbook
Set wb = Workbooks.Open(FOLDER & XLS_FILE, 1, 1)
Set ws = wb.Sheets("Sheet1")
' create XML document
s = XML
For r = 2 To ws.Cells(Rows.Count, "A").End(xlUp).Row
s = s & " <User ID=""" & ws.Cells(r, 1) & """" & _
" ForceAuthentication=""false"" Password=""1234""" & _
" EMail=""" & ws.Cells(r, 2) & """>" & vbCrLf
s = s & " <Name>" & ws.Cells(r, 1) & "</Name>" & vbCrLf
For Each e In TextInParentheses(ws.Cells(r, 3).Value)
s = s & " <UserGroupLink UserGroupID=""" & Trim(e) & """/>" & vbCrLf
Next e
s = s & " </User>" & vbCrLf
Next
s = s & " </UserList>" & vbCrLf & "</Core-data>"
'wb.Close false 'close source workbook
' save to same path as running code
savePath = ThisWorkbook.Path & "\" & XML_FILE
PutContent savePath, s
MsgBox "Xml created at '" & savePath & "'", vbInformation
End Sub
'all texts enclosed in parentheses as a collection
Function TextInParentheses(txt As String)
Dim re As Object
Dim allMatches, m, col As New Collection
Set re = CreateObject("VBScript.RegExp")
re.Pattern = "\(([^\)]+)\)"
re.ignorecase = True
re.Global = True
Set allMatches = re.Execute(txt)
For Each m In allMatches
col.Add Trim(m.submatches(0))
Next m
Set TextInParentheses = col
End Function
'Save text `content` to a text file at `f`
Sub PutContent(f As String, content As String)
CreateObject("scripting.filesystemobject"). _
opentextfile(f, 2, True).write content
End Sub
Need to convert excel data into XML format.
'vba code to convert excel to xml
Sub vba_code_to_convert_excel_to_xml()
Set wb = Workbooks.Open("C:\temp\testwb.xlsx")
wb.SaveAs fileName:="C:\temp\testX.xml", FileFormat:= _
xlXMLSpreadsheet, ReadOnlyRecommended:=False, CreateBackup:=False
Kindly let me how to do this in VBA or provide a link where I can refer. Thanks in Advance.
For a simple case one way would be to build the xml line by line
Sub vba_code_to_convert_excel_to_xml2()
Const FOLDER = "C:\temp\"
Const XLS_FILE = "testwb.xlsx"
Const XML_FILE = "testX.xml"
Const XML = "<?xml version=""1.0"" encoding=""utf-8""?>" & vbCrLf & _
"<Core-Information ContextID=""Context1"" WorkspaceID=""Main"">" & vbCrLf & _
" <UserList>" & vbCrLf
Dim wb As Workbook, ws As Worksheet, ar, s As String
Dim iLastRow As Long, r As Long, n As Integer
' open source workbook
Set wb = Workbooks.Open(FOLDER & XLS_FILE, 1, 1)
Set ws = wb.Sheets("Sheet1")
iLastRow = ws.Cells(Rows.Count, "A").End(xlUp).Row
' create XML document
'<User ID="Aravind" ForceAuthentication="false" Password="1234" EMail="Aravind#gmail.com">
' <Name>Aravind</Name>
' <UserGroupLink UserGroupID="Sports"/>
'</User>
s = XML
For r = 2 To iLastRow
s = s & " <User ID=""" & ws.Cells(r, 1) & """" & _
" ForceAuthentication=""false"" Password=""" & ws.Cells(r, 2) & """" & _
" EMail=""" & ws.Cells(r, 3) & """>" & vbCrLf
s = s & " <Name>" & ws.Cells(r, 1) & "</Name>" & vbCrLf
ar = Split(ws.Cells(r, 4), ",")
For n = LBound(ar) To UBound(ar)
s = s & " <UserGroupLink UserGroupID=""" & Trim(ar(n)) & """/>" & vbCrLf
Next
s = s & " </User>" & vbCrLf
Next
s = s & " </UserList>" & vbCrLf & "</Core-Information>"
' save
Dim fso, ts
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.createtextfile(FOLDER & XML_FILE)
ts.write s
ts.Close
MsgBox "Xml created to " & FOLDER & XML_FILE
End Sub
I have a function to parse an xml document received from the tracking system of TNT courier,
this is example of a query url i'm using:
https://www.tnt.it/tracking/getXMLTrack?WT=1&ConsigNos=RL38536236
the function worked correctly on all PCs until yesterday,
when on some PCs the method .Load(URL) of DOMDocument object returns false result and the DocumentElement property is null,
the thing is: if i browse to that url (i used firefox, chrome, edge, iexplore)
the xml is showed correctly!
this is the code:
Function TrackTNTlist(LDV As String) As Collection
Dim TNTlist As New Collection
Dim Obj As MSXML2.DOMDocument60
Dim Verifica As Boolean
Dim XMLTNT As String
Dim NodoLista As IXMLDOMNodeList
Dim NodoSingolo As IXMLDOMNode
Dim Nome As IXMLDOMNode
Dim DataConsegna As IXMLDOMNode
Dim NomeRicevente As IXMLDOMNode
Dim Destinatario As IXMLDOMNode
Dim ConsignmentDetails As IXMLDOMNode
Dim DataPrevConsegna As IXMLDOMNode
Dim NuovaLDV As IXMLDOMNode
Dim Dest As String, DatiSped As String
On Error GoTo RigaErrore
XMLTNT = "https://www.tnt.it/tracking/getXMLTrack?WT=1&ConsigNos=" & LDV
Set Obj = New MSXML2.DOMDocument60
Obj.async = False
Verifica = Obj.Load(XMLTNT)
If Verifica = True Then
MsgBox "File XML " & XMLTNT & "loaded"
Else
MsgBox "File XML NOT loaded"
TNTlist.Add "ERROR - XML tracking data not loaded"
Exit Function
End If
Set NodoSingolo = Obj.DocumentElement.SelectSingleNode("Consignment/StatusDetails/StatusDescription")
If NodoSingolo Is Nothing Then
TNTlist.Add "LDV non trovata"
Else
Set NodoList = Obj.DocumentElement.SelectNodes("Consignment/StatusDetails")
Set ConsignmentDetails = Obj.DocumentElement.SelectSingleNode("Consignment/ConsignmentDetails")
DatiSped = ""
DatiSped = "LETTERA DI VETTURA: " & LDV & Chr(10)
If Not ConsignmentDetails Is Nothing Then
DatiSped = DatiSped & "RIF. MITTENTE: " & ConsignmentDetails.ChildNodes(0).Text & Chr(10)
DatiSped = DatiSped & "TIPO SERVIZIO: " & ConsignmentDetails.ChildNodes(1).Text & Chr(10)
DatiSped = DatiSped & "NUM. COLLI: " & ConsignmentDetails.ChildNodes(3).Text & Chr(10)
End If
Set NodoSingolo = Obj.DocumentElement.SelectSingleNode("Consignment/StatusDetails/StatusDescription")
Dest = ""
Set DataConsegna = Obj.DocumentElement.SelectSingleNode("Consignment/DeliveryDate")
Set NomeRicevente = Obj.DocumentElement.SelectSingleNode("Consignment/CollectionName")
Set Destinatario = Obj.DocumentElement.SelectSingleNode("Consignment/ReceiverDetails")
Set DataPrevConsegna = Obj.DocumentElement.SelectSingleNode("Consignment/DueDate")
Set NuovaLDV = Obj.DocumentElement.SelectSingleNode("Consignment/HeldInDepotDetails/HID1ReplacingDoc")
If NodoSingolo.Text = "Spedizione consegnata" Then
Dest = "CONSEGNATA A: " & Chr(13)
Else
Dest = "PREVISTA CONSEGNA A: " & Chr(10)
End If
If Not Destinatario Is Nothing Then
Dest = Dest & Destinatario.ChildNodes(4).Text
Dest = Dest & " (" & Destinatario.ChildNodes(6).Text & ")" & Chr(10)
End If
If Not DataPrevConsegna Is Nothing Then
Dest = Dest & DataPrevConsegna.ChildNodes(0).Text & Chr(10)
End If
If Not DataConsegna Is Nothing Then
Dest = Dest & "Data consegna: " & DataConsegna.Text & Chr(10)
End If
If Not NomeRicevente Is Nothing Then
Dest = Dest & "Ha ritirato: " & NomeRicevente.Text & Chr(10)
End If
If Not NuovaLDV Is Nothing Then
Dest = Dest & "NUOVA LETTERA DI VETTURA: " & NuovaLDV.Text & Chr(10)
End If
Dest = Dest & "Dettaglio tracking:" & Chr(10)
TNTlist.Add DatiSped & Chr(10) & Dest & Chr(10)
For Each Nome In NodoList
TNTlist.Add Nome.ChildNodes(1).Text
TNTlist.Add Nome.ChildNodes(2).Text
Next
End If
salto = 1
If salto <> 1 Then
Set NodoSingolo = Obj.DocumentElement.SelectSingleNode("Consignment/StatusDetails/StatusDescription")
If NodoSingolo Is Nothing Then
TNTlist.Add "LDV non trovata"
Else
If NodoSingolo.Text = "Spedizione consegnata" Then
Set DataConsegna = Obj.DocumentElement.SelectSingleNode("Consignment/DeliveryDate")
Set NomeRicevente = Obj.DocumentElement.SelectSingleNode("Consignment/CollectionName")
Set Destinatario = Obj.DocumentElement.SelectSingleNode("Consignment/ReceiverDetails")
Dest = Destinatario.ChildNodes(4).Text
Dest = Dest & " (" & Destinatario.ChildNodes(5).Text & ")"
TNTlist.Add NodoSingolo.Text & " : " & Dest & " - " & NomeRicevente.Text & " - " & DataConsegna.Text
TNTlist.Add DataConsegna.Text
End If
End If
End If
Set TrackTNTlist = TNTlist
Exit Function
RigaErrore:
MsgBox Err.Number & vbNewLine & Err.Description
Application.EnableEvents = True
Resume Next
End Function
the problem occurs only in few pcs,
they have the same system configuration,
below two screen shots, one from a pc where the function work correctly ad one from another where the problem occurs.
debug screenshot of correct execution
debug screenshot of error execution
in both pcs browsing to the url show the xml correctly.
Could anyone help me to understand what might cause the problem?
Thanks a lot!
Francesco
I am trying to utilize a "dictionary" script that I found to define words in a column. VB throws out that error at me and I am clueless as to how to fix it. AM I using anything that a vba app script could understand? Here is the website that I am using to insert this function into excel: https://script.google.com
Code:
Function DefineWord(wordToDefine As String) As String
' Array to hold the response data.
Dim d() As Byte
Dim r As Research
Dim myDefinition As String
Dim PARSE_PASS_1 As String
Dim PARSE_PASS_2 As String
Dim PARSE_PASS_3 As String
Dim END_OF_DEFINITION As String
'These "constants" are for stripping out just the definitions from the JSON data
PARSE_PASS_1 = Chr(34) & "webDefinitions" & Chr(34) & ":"
PARSE_PASS_2 = Chr(34) & "entries" & Chr(34) & ":"
PARSE_PASS_3 = "{" & Chr(34) & "type" & Chr(34) & ":" & Chr(34) & "text" & Chr(34) & "," & Chr(34) & "text" & Chr(34) & ":"
END_OF_DEFINITION = "," & Chr(34) & "language" & Chr(34) & ":" & Chr(34) & "en" & Chr(34) & "}"
Const SPLIT_DELIMITER = "|"
' Assemble an HTTP Request.
Dim url As String
Dim WinHttpReq As Variant
Set WinHttpReq = CreateObject("WinHttp.WinHttpRequest.5.1")
'Get the definition from Google's online dictionary:
url = "http://www.google.com/dictionary/json?callback=dict_api.callbacks.id100&q=" & wordToDefine & "&sl=en&tl=en&restrict=pr%2Cde&client=te"
WinHttpReq.Open "GET", url, False
' Send the HTTP Request.
WinHttpReq.Send
'Print status to the immediate window
Debug.Print WinHttpReq.Status & " - " & WinHttpReq.StatusText
'Get the defintion
myDefinition = StrConv(WinHttpReq.ResponseBody, vbUnicode)
'Get to the meat of the definition
myDefinition = Mid$(myDefinition, InStr(1, myDefinition, PARSE_PASS_1, vbTextCompare))
myDefinition = Mid$(myDefinition, InStr(1, myDefinition, PARSE_PASS_2, vbTextCompare))
myDefinition = Replace(myDefinition, PARSE_PASS_3, SPLIT_DELIMITER)
'Split what's left of the string into an array
Dim definitionArray As Variant
definitionArray = Split(myDefinition, SPLIT_DELIMITER)
Dim temp As String
Dim newDefinition As String
Dim iCount As Integer
'Loop through the array, remove unwanted characters and create a single string containing all the definitions
For iCount = 1 To UBound(definitionArray) 'item 0 will not contain the definition
temp = definitionArray(iCount)
temp = Replace(temp, END_OF_DEFINITION, SPLIT_DELIMITER)
temp = Replace(temp, "\x22", "")
temp = Replace(temp, "\x27", "")
temp = Replace(temp, Chr$(34), "")
temp = iCount & ". " & Trim(temp)
newDefinition = newDefinition & Mid$(temp, 1, InStr(1, temp, SPLIT_DELIMITER) - 1) & vbLf 'Hmmmm....vbLf doesn't put a carriage return in the cell. Not sure what the deal is there.
Next iCount
'Put list of definitions in the Immeidate window
Debug.Print newDefinition
'Return the value
DefineWord = newDefinition
End Function
This looks like visual basic, Google uses Apps script which is essentially javascipt. In Javascript you terminate statements with semicolon, that's what it's looking for.
link here:Google Help Forum
Folks....For some years now I have used the following function in one of my Excel macros to help me compose photo captions from English into French. This AM it started throwing an error, which pointed to the .Send command in the code below:
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
When I copy/paste the contents of strURL directly into IE, the first time I got a CAPTCHA and a comment that they are checking for 'robots'. The second time it worked directly. They must be setting a cookie??
Is there anyway around this? Or another way to get simple phrases translated in a macro?
Thanks....RDK
OK, done with Google Translate! It is no longer free for VBA usage even as small as mine. Now using Microsoft Translator via VBA. Just signed up on Microsoft Azure Marketplace and get 2 million character/month for free.
I've been using this system for several months now and it works as good as Google Translate did. Not perfect, but good enough....RDK
The following is just beta-realisation of a google-translation module for vba:
(used it for fast translation of a software)...
maybe you need manually check the text afterwards for correctness.
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 = "de","en", ... (TargetLanguage)
srcLang = "de","en", ... (SourceLanguage)
(Attention, its just a workaround!)
Please refer to get Phonetic of Google transcript (As string)
(It's just below TextBox, when translate from English using one word)