AppleScript/Automator Folder Action to Convert Excel to CSV - excel

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.

Related

Why isn't my script able to locate my excel file when given correct filepath?

I have a .vbs script that opens two excel files and copies the contents of a sheet from the first file into the second file. It's supposed to run daily via task scheduler.
The script ran normally until the excel files in question were recently modified and slightly renamed - I went through the script and edited the filenames accordingly after the changes were made, triple checking that the names and filepaths matched up.
Everything ran fine for a few weeks after the changes but now the script fails immediately after starting, giving me an error claiming that the file can't be located even though the file is located at the given path. The error code is 800A03EC.
This is the first chunk of code in the script, including line 7 which seems to be throwing the error:
Dim objApp ' as excel object
Dim x, y ' as workbook
Set objApp = CreateObject("Excel.Application")
objApp.DisplayAlerts = False
objApp.Visible = False
Set x = objApp.Workbooks.Open("S:\Work (Public)\PORT MGMT & TRADING\PORT MGMT FORMS\ORION_FPFOCUS.xlsm")
Set y = objApp.Workbooks.Open("S:\Work (Public)\PORT MGMT & TRADING\PORT MGMT FORMS\FPFocusPasteSpecialValues.xlsb")
Dim WSx, WSy ' as excel worksheet
Set WSx = x.Worksheets("FPSUP")
Set WSy = y.Worksheets("FPFOCUS-COPY")
WSy.Range("B1").value = FormatDateTime(Now)
objApp.Application.Run "ORION_FPFOCUS.xlsm!Auto_Open"
The excel files in question are both located in the same directory:
S:\Work (Public)\PORT MGMT & TRADING\PORT MGMT FORMS\ORION_FPFOCUS.xlsm
S:\Work (Public)\PORT MGMT & TRADING\PORT MGMT FORMS\FPFocusPasteSpecialValues.xlsb
And the script is located here:
C:\Users\bserv\Documents\CopyFPFocus.vbs
The S drive isn't a physical drive, it's a virtual drive hosted by a service called Workplace. I can navigate through it and open the excel files manually just fine.
I initially thought it was a user privilege issue with task scheduler, but I've selected the 'run with highest privileges' option and the script is still failing. I also went through the privacy/trust settings in Excel to make sure the script wasn't being denied access, but I don't see any settings that would disable the script from working, and I also know that all these settings haven't changed since the script was working, so I don't see how they could be potential causes.
When I try running the code manually via cscript in the command line, it returns this error:
C:\Users\bserv\Documents\CopyFPFocus.vbs(25, 4) (null): The remote procedure call failed.
This is line 25 of the script for reference:
objApp.Run "RefreshAllStaticData"
When I try again by running command prompt as an admin, I get the same error I got initially. Sorry, is it possible the file was moved renamed or deleted.
The part that really confuses me is that the script ran fine for some time after the changes - so I'm really unsure about what actually changed to cause this issue to randomly pop up.
One other thing I've noticed is that upon opening the excel files I get a popup saying they're in use and locked for editing by me. I can't remember if this popup was showing up before the issue started. The other users on the network have been accessing these files regularly long before the script started failing, so I don't see how that could be the issue. The error code/message also doesn't seem to correspond with this being the problem.
I'd appreciate any help or insight into this issue. Thank you!

Opening the latest downloaded CSV file with Excel using AppleScript

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

Load contents of .rtf file into RichTextBox Control

I am trying to build an Excel application with UserForms. In a UserForm, I've successfully added RichTextBoxes. I have also successfully coded a button to save all RichTextBox contents in an .rtf file.
This is where I'm stuck:
There does not seem to be a way to load the contents of an rtf file into a RichTextBox.
I've flipped through 5 pages of various google searches, but none gave any clues towards Excel VBA... all were on C#...
Speaking of C#, when I try something similar such as .rtfOne.LoadFile(filePath) I get an error:
Run-Time error '75':
The specified Path/file name cannot be accessed or is invalid.
Code I tried:
Dim filePath As String
filePath = "C:\Users\Donkey\Desktop\Test One\" & Cells(1,1)
UserForm.richtextbox1.LoadFile(filePath & "richtextfile.rtf")
I have included a MsgBox in my code to see how the compiler reads this line, it is read correctly as:
C:\Users\Donkey\Desktop\Test One\2019AA-10000V1richtextfile.rtf

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

A simple way to save a file version to a child folder and generate/increment a log?

I looked to TortoiseSVN and TortoiseHG... bit too much for me and I don't want to setup a structure where the files will be saved. All I want is:
When saving a file, first saves the file.
Then if there isn't in file's folder a sub-folder called "History", it creates it.
Then Copies the file to "History" and gives it the first available number suffix as "_[version]".
Then, if is no txt file, in the file's folder, called "[filename].[extension]_Notes.txt", it creates it and adds a line with:
Version: [version] " of the " [filename] " saved at: " [date]
Now how would this run from any application? Dunno. Maybe have a button in the file save dialog?
I'm asking this because I'm just one guy working and not on huge projects and 99% of the time I would just like to have a localized versioning, set on a local sub-folder and a log to track the versions and dates.
Is this super easy with Tortoise and I'm being a mule?
Cheers

Resources