In Excel, if I enter the word "PIZZA" into a cell, select it, and SHIFT+F7, I can get a nice English dictionary definition of my favorite food. Pretty cool.
But I'd like a function that does this. Something like '=DEFINE("PIZZA")'.
Is there a way through VBA scripts to access Microsoft's Research data? I was considering using a JSON parser and a free online dictionary, but it seems like Excel has a nice dictionary built-in. Any ideas on how to access it?
In case VBA's Research object doesn't work out, you can try the Google Dictionary JSON method as so:
First, add a reference to "Microsoft WinHTTP Services".
After you see my mad, JSON parsing skillz, you may also want to add your favorite VB JSON parser, like this one.
Then Create the following Public Function:
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
After that, it's just a matter of putting the function in your cell:
=DefineWord("lionize")
via the Research object
Dim rsrch as Research
rsrch.Query( ...
To query, you need the GUID of a valid web service. I haven't been able to find the GUID's for Microsoft's built in service though.
Related
I am wishing to export data from an Excel sheet to multiple CSV files using an Array, I have written the code that creates the export without issue, but I cannot seem to get my head around assigning the initial values to an Array and then using some kind of while loop from the data in the Array to produce the desired exports.
The unique values I wish to hold in the Array are located in Column A of sheet 1, obviously the values in the column are not unique, but I only wish to reference (add to the Array) once.
Once I have the values in the Array I want to place the code in a while loop to export the data based on the unique value in the Array.
Below in a snippet of my current code, which in isolation works fine;
Public InvDate
Sub ExportAccLinesLoop()
Dim fso, FilePathName, FilePath, Station, StationName, StationDate, Exp, d1, WC, dd, mm, yy
dd = Left(InvDate, 2)
mm = Mid(InvDate, 4, 2)
yy = Right(InvDate, 2)
FilePath = "\\Sunbury-xxx\xxx\Parcels\Attachments\"
FilePathName = FilePath & "Tmp.csv"
Worksheets("Sheet1").Activate
Set rRange = Worksheets("Sheet1").Range("A1", Range("A" & Rows.Count).End(xlUp))
Set fso = CreateObject("Scripting.FileSystemObject")
If Not fso.FolderExists(FilePath) Then fso.CreateFolder (FilePath) 'create folder if it does not exist
Set inputFile = fso.OpenTextFile(FilePathName, 8, True)
inputFile.WriteLine (Chr(34) & "Rate Acc" & Chr(34) & "," & Chr(34) & "Movement" & Chr(34) & "," & Chr(34) & "Ledger Acc" & Chr(34)) ‘Write Header values
inputFile.Close
For Each rCell In rRange
If rCell.Value = "WAR" Then
RateAcc = rCell(1, 1)
DelCol = rCell(1, 2)
LedgerAcc = rCell(1, 3)
If Not fso.FolderExists(FilePath) Then fso.CreateFolder (FilePath) 'create folder if it does not exist
Set inputFile = fso.OpenTextFile(FilePathName, 8, True)
inputFile.WriteLine (Chr(34) & RateAcc & Chr(34) & "," & Chr(34) & DelCol & Chr(34) & "," & Chr(34) & LedgerAcc & Chr(34)) ‘Write Line values
inputFile.Close
End If 'rCell
Next rCell
fso.CopyFile FilePathName, FilePath & yy & mm & dd & "-" & LedgerAcc & "-" & RateAcc & "-" & "TRAN.csv" 'Copy Tmp.csv to correct filename
fso.DeleteFile FilePathName 'Delete Tmp.csv
End Sub
I assume the while loop will start after Set rRange, indeed the unique Array values will come from the same range, but I'm stuck.
Any ideas?
Dim objDict As Object
Dim key As Variant
Set objDict = CreateObject("System.Collections.ArrayList")
With ThisWorkbook.ActiveSheet
With .Range("A2", .Range("A" & .Rows.Count).End(xlUp))
For Each key In .Value
If Not objDict.Contains(key) Then objDict.Add key
Next
End With
End With
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
I have created VBA code for sending mails with different attachments to different addresses, via Thunderbird. The code looks correct but while creating particular mail bodies it uses still the first values. And the strange fact is that in the debugging window all looks correct and the values are changing.
$
Option Explicit
Sub SendMailThunder_Click()
Dim strEmpfaenger1 As String
Dim strBetr As String
Dim strBody As String
Dim strFile2 As Variant
Dim strTh As String
Dim strCommand As Variant
Dim Nazev As String
Dim vysledek As Variant
Dim Seznam As Excel.Worksheet
Dim PS As Integer
Dim y As Long
Set Seznam = ThisWorkbook.Worksheets("Ridici")
' number of items in the column
PS = Seznam.Cells(Rows.Count, 11).End(xlUp).Row
With Seznam
For y = 4 To PS
' Name of attachment
Nazev = .Cells(y, 12).Value
' selected email
strEmpfaenger1 = .Cells(y, 15).Value
strBetr = .Range("O1")
strBody = .Range("O2")
strTh = "C:\Users\alois.konecny\AppData\Local\Mozilla Thunderbird\thunderbird.exe"
' path to attachment
cesta = .Range("N1")
' attachment including path
priloha = "\" & Nazev & ".xls"
vysledek = cesta & priloha
strFile2 = vysledek
strCommand = strCommand & " -compose " & "to=" & Chr(34) & strEmpfaenger1 & Chr(34)
strCommand = strCommand & ",subject=" & Chr(34) & strBetr & Chr(34)
strCommand = strCommand & ",body=" & Chr(34) & strBody & Chr(34)
strCommand = strCommand & ",attachment=" & "file:///" & Replace(strFile2, "\", "/")
Shell strTh & strCommand, vbNormalFocus
Next y
End With
End Sub
$
The code is a bit hard to read, but have your tried this:
file://
instead of
file:///
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)
I'm trying to search for a file, in d:\ folder with the name Division_Application_Partner.xlsx where Division Application and Partner are variables holding string values.
This is the code I gave:
Set WorkbookPath = Dir(path & Division + "_" + Application + "_" + TradingPartner + ".xlsx")`enter code here`
It throws an error saying " Compile Error: Type Mismtach "
Is the name of the file im giving wrong
Here's the code:
Dim WorkbookPath As WorkBook
Dim path as String
Division = Range("C11").Value
Application = Range("C15").Value
TradingPartner = Range("C19").Value
path = "d:\"
'MsgBox (path)
'MsgBox (Division)
'MsgBox (Application)
MsgBox (TradingPartner)
If Len(Dir(path & Division & "_" & Application & "_" & TradingPartner & ".xlsx")) = 0 Then
Set WorkbookPath = Division & "_" & Application & "_" & TradingPartner & ".xlsx"
End If
I tried concatenating using & like you suggested. Still it shows the same error.
You try assign string to object, this why you getting an error
Dim WorkbookPath As WorkBook
Better try
Dim myWkb as Workbook
Set myWkb = Workbooks.Open(your_concat_string)
and dont use reserved words
Application
Finally
Sub test()
Dim wkbExternWorkbook As Workbook
Dim strPath As String
Dim strDivision As String, strApplication As String, strTradingPartner As String
strDivision = Range("C11").Value
strApplication = Range("C15").Value
strTradingPartner = Range("C19").Value
strPath = "D:\"
If Len(Dir(strPath & strDivision & "_" & strApplication & "_" & strTradingPartner & ".xlsx")) <> 0 Then
Set wkbExternWorkbook = Workbooks.Open(strPath & strDivision & "_" & strApplication & "_" & strTradingPartner & ".xlsx")
End If
End Sub
I would start with using & exclusively for string concatenation. The use of + is primarily for adding numbers though it can concatenate strings. However, there are all sorts of caveats to that when using option strict and so forth, so you're better off using what was intended.
The other thing you should do is actually output all those variables before attempting to concatenate or pass them to Dir. Something like:
MsgBox "[" & path & "]"
repeated for all the others as well. The output of that may well point to the problem.
Try this:
Sub test()
Dim application As Variant
Dim division As Variant
Dim WorkbookPath As String
Dim tradingpartner As Variant
Dim path As String
division = Range("C11").Value
application = Range("C15").Value
tradingpartner = Range("C19").Value
path = "d:\"
'MsgBox (path)
'MsgBox (Division)
'MsgBox (Application)
MsgBox (tradingpartner)
If Len(Dir(path & division & "_" & application & "_" & tradingpartner & ".xlsx")) = 0 Then
Workbooks.Add
ActiveWorkbook.SaveAs division & "_" & application & "_" & tradingpartner & ".xlsx"
End If
End Sub
You would first add the workbook and then save it using the created name.