Opening the latest downloaded CSV file with Excel using AppleScript - excel

I need to find a way to automatically open the last downloaded CSV file using excel
I've been trying to find some codes and adapt it to my needs but it won't work
The code below will open the latest file with numbers as expected. I can't change the default use of numbers for CSV files
tell application "Finder"
open last item of (sort (get files of (path to downloads folder)) by creation date)
end tell
When I change to tell application "excel", it returns an error.
"Expected “,” but found “by”."
Thanks for your help!

The Finder's open command has a using parameter that lets you specify an application to open the file. i.e., code it this way:
tell application "Finder"
set theFolder to folder (path to downloads folder)
set latestFile to last item of (sort (files of theFolder) by creation date)
open latestFile using (path to application "Microsoft Excel")
end tell

You have to coerce the Finder item to a file path. This path reference can be opened with Excel
tell application "Finder"
set latestFile to last item of (sort (get files of (path to downloads folder)) by creation date) as text
end tell
tell application "Microsoft Excel" to open latestFile

Related

'Save As' of object '_workbook' failed

I am trying to save a workbook as xlsm, this is the code I use:
ThisWorkbook.SaveAs Filename:="path\workbook_name.xlsm", FileFormat:=xlOpenXMLWorkbookMacroEnabled
I have done some testing, and It does in fact save in both a private folder and a public or shared folder
however when I save it in a shared folder I also get this:
Run-time error '1004' Method 'Save As' of object '_workbook' failed
why do I get error message when it is saved in a public/shared folder, or onedrive?
In your string containing path there is variable "path" i suppose. Then you should write it like this:
Dim path as String: path = "C:\Users\xxx\Desktop"
ThisWorkbook.SaveAs Filename:=path & "\workbook_name.xlsm", FileFormat:=xlOpenXMLWorkbookMacroEnabled
Or you can hardcode full path (but i recommend using variables - first example).
ThisWorkbook.SaveAs Filename:="C:\Users\xxx\Desktop\file.xlsm", FileFormat:=xlOpenXMLWorkbookMacroEnabled
Then when you can save it manually and you have permissions then i have no idea since i normally save files to shared folders and network drives... Maybe your specific path is wrong. It is best to save using servername and folders...
path = "\\servername\folder1\folder2\workbook_name.xlsm"
Because sometimes when you refefer to mapped drive for example X:\folder2 then you must ensure that all users have it mapped in same way (someone uses X someone uses R etc.). And if path is correct then only other way i can think of it is permission issue, but if you can save it manually then i have sadly no idea... :)

custom function in excel using vba that works in any matchine

I have created a custom function via vba in excel. If I use it in my computer, it works ok, but if I change the file to another computer (where this computer also has the created function), it does not work. I must change the path of the created function. Is there any way to not change the path everytime I copy the file into another computer?
='C:\Users\Usuario1\Documents\Complementos\BondsTIRMDuration.xlam'!TIrbonds($A2;F2;'C:\Users\Usuario1\Documents\Complementos\AsBusinessDay.xlam'!asbusinessday('C:\Users\Usuario1\Documents\Complementos\AsBusinessDay.xlam'!PrevBusinessDay(HOY())))*100
Solution 1: You could use a common paths in both computers
(for example: C:\work , C:\Work2)
Solution 2: You could put all files in the same path (C:\work), then you only need the to put the file name
='BondsTIRMDuration.xlam'!TIrbonds($A2;F2;'AsBusinessDay.xlam'!asbusinessday('AsBusinessDay.xlam'!PrevBusinessDay(HOY())))*100
Just save your add-in in the correct path on every computer.
It should be something like:
C:\Users\YOURNAME\AppData\Roaming\Microsoft\AddIns\
See Install and Use Excel Add-ins to determine the correct path.
If your add-in is installed correctly you should be able to run your user defined function without a path.
You can call special folder with application.
MsgBox Application.DefaultFilePath
This example will be: C:\Users\Usuario1\Documents
'Here are a few VBA path functions
MsgBox Application.Path
MsgBox Application.DefaultFilePath
MsgBox Application.TemplatesPath
MsgBox Application.StartupPath
MsgBox Application.UserLibraryPath
MsgBox Application.LibraryPath
You can too create wscrit object to call another paths, for example:
MsgBox CreateObject("Wscript.Shell").SpecialFolders("Desktop")
Example folders for Wscript.shell object:
AllUsersDesktop
AllUsersStartMenu
AllUsersPrograms
AllUsersStartup
Desktop
Favorites
Fonts
MyDocuments
NetHood
PrintHood
Programs
Recent
SendTo
StartMenu
Startup
Templates
And execute a macro like this,(allways have to use same directory):
Sub Macro()
AddIns.Add Filename:=Application.DefaultFilePath & "\Complement.xlam"
AddIns("Complement").Installed = True
End Sub

How to discover Oleobject ClassType of files?

I'm stuck how to determine files' Classtypes needed to use in code to embed these files into a Word document:
Selection.InlineShapes.AddOLEObject ClassType:="AcroExch.Document.11", _
FileName:="C:\Work\Dashbaord & ".pdf", LinkToFile:=False, _
DisplayAsIcon:=False
I need to embed csv, pdf, xlsx and txt files. How I can automatically loop all files in folders and automatically determine the ClassType of each?
In order to insert a file as an OLE Object the file type needs to have an available OLE Server installed on the machine, or it needs to be in a format that the Windows Packager mechanism can "wrap up" into an OLE type. Before you go this route you need to ensure that anyone who tries to work with such a document has corresponding OLE Server software installed on the machine on which the document is opened. Just because the machine that creates an embedded OLE object can do so doesn't mean another machine can work with the result, later on.
OLE Server software will be noted in the Registry. The Microsoft Office applications (Word, Excel, PowerPoint, etc.) are able to function as OLE Servers. In the Registry you'll find corresponding entries such as Word.Document and Excel.Workbook... or AcroExch.Document for PDF files if Microsoft Office and the Adobe Acrobat Reader are installed.
One way to figure out which ClassTypes to use would be to manually insert each file type and inspect the resulting Embed field code.
To look the ClassTypes up in the Registry, something like the following code sample can be used in Word. Word has the function System.PrivateProfileString that wraps up a Windows API call to the Registry. It can be used to retrieve and to write information. (This code does not loop the files in a directory as the question was about how to determine the ClassType. For the sake of simplicity a file extension is hard-coded.)
A file type that does not have an OLE Server won't have a . in the default value of the Registry key. A .txt file, for example, is listed as txtfile. You may have to watch out for some file types; for example on my installation a csv file is listed as Excel.CSV, which may not be what you want...
Sub RetrieveOLEInfo()
Dim fileExt As String
Dim regKey As String
Dim oleServer As String
fileExt = "docx"
regKey = "HKEY_Classes_Root\."
oleServer = System.PrivateProfileString("", regKey & fileExt, "")
'Debug.Print oleServer
If InStr(oleServer, ".") = 0 Then
Debug.Print "Insert as a Package"
Else
Debug.Print "Insert as: " & oleServer
End If
End Sub

AppleScript/Automator Folder Action to Convert Excel to CSV

I'm running into a "Grant Access" problem with Office 2016 where I have to manually click "Grant Access" if I'm opening a new file with Automator. I found this answer for how to get around it (by using a file object or an alias object instead of a string):
tell application "Microsoft Excel"
activate
open file "Macintosh HD:Users:path:to:file"
end tell
But since I'm using an Automator folder action, I'm not sure how to get that file path where it needs to be. Most of the examples I found has the AppleScript use choose folder with prompt but since the whole point of this is to be fully automated, that's not going to work.
The idea is:
Excel file gets downloaded into "ForSQL" folder
Folder action prompts xls file to convert into csv
csv then opens in TextWrangle to ensure it stays in UTF-8
Then moves it to official "SQL" folder
Closes all the applications it opened and deletes whatever it moved from the "ForSQL" folder
But I'm open to better suggestions that get to the same end result.
This is my Automator workflow so far -- but it looks like I need to replace the 'Convert Format of Excel Files' step with AppleScript to get the "Grant Access" pop-up to go away. It's a folder action that starts when something hits the "ForSQL" folder:
I am not sure to understand what you want to do with textWrangle, but the script bellow does all steps before and after, only using Applescript (no need for Automator actions) :
--this choose file must be replaced by your "input" of automator folder items
set Fxl to choose file --the Excel file to be processed
-- define here your destination SQL folder
-- for my tests, I used a folder mySQL on my Desktop
set SQLFolder to ((path to desktop folder) as string) & "mySQL"
tell application "Finder" to set ForSQL to (container of Fxl) as string
--define new name by replacing current extension (xls, xlsx, xlsm, xml) by "csv"
tell application "Finder"
set N to name of Fxl
set NbExt to length of ((name extension of Fxl) as string)
set newname to (text 1 thru -(NbExt + 1) of N) & "csv"
end tell
--convert to CSV and close
tell application "Microsoft Excel"
open Fxl
tell workbook 1
tell sheet 1 to save in (ForSQL & newname) as CSV file format
close without saving
end tell
end tell
-- add eventually your TextWrangle step here (?)
-- delete source file and move csv to proper folder
tell application "Finder"
delete Fxl
move file (ForSQL & newname) to folder SQLFolder
end tell
In practice you can run all this in full applescript folder action.
Replace the "set Fxl to choose..." by "on adding folder items...".
In this case you must insert the script above in a repeat loop to process all files drops in the folder.
However, you may have some issues using folder action script, because system will trigger your script again at the time you are creating the new CSV file (again in the same folder !).
The work around I suggest is to use folder action script to get the file dropped in ForSQL, move it to an other "temp_ForSQL" and run this script using the moved file. Doing so, the cvs will be added to temp_forSLQ, without triggering new folder action script.
I hope it is clear enough...if not, just let me know.

VBA - How to get the last modified file or folder in a directory in Excel 2010

What I want to do is more complex than selecting a file from a list of files. I will start in a directory, then I want to change to the most recently modified directory. I then want to repeat that process in a sub-directory, and then, inside of that, I want to select the most recently modified excel file and open it.
What is the best approach to do this?
What objects / methods should I be looking into?
The simplest function is
FileDateTime(pathname)
where pathname can be a directory for folder.
Alternatively, you can use the FileSystemObject object, DateLastModified property:
Dim fileModDate As String
Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.GetFile(<filenamestringhere>)
fileModDate = f.DateLastModified
All of the above can be explored in VBA help.

Resources