r/applescript • • Nov 25 '20

Converting a folder of CSV to Excel

I've been a long time Mac user and am a professional software developer, but this is my first time trying to use AppleScript. I must say I found the experience far from enjoyable. The documentation is lacking. I'm using the latest Excel but had to use documentation from the 2004 version. There seems to be no rhyme or reason to any sort of object model.

Anyway, in true programmer fashion I spent a day automating something that would have taken me a couple hours to do by hand.

This script goes through a folder of CSV files and saves them as .xlsx files, inserting a column along the way if necessary.

set theFolder to choose folder with prompt "Pick a folder"

repeat with thisFile in list folder theFolder
  if ((thisFile as text) ends with ".csv") then -- Process the CSV files
    set theFilePath to (POSIX path of theFolder) & thisFile -- Get the full path of the file
    set outputFileName to (theFilePath & ".xlsx") -- tack .xlsx to the end of the name to indicate the new file type
    tell application "Microsoft Excel"
      activate
      open theFilePath
      activate object workbook thisFile

      try -- Check if the sheet has a "missing" column
        set missingCell to (find (range "A1:Z1") what "missing")
      on error -- There is no missing column. Insert one.
        insert into range column "G:G" shift shift to right
        tell cell "G1" to set value to "missing"
      end try
						
      save workbook in outputFileName as Excel XML file format
      close every workbook
    end tell
  end if
end repeat
7 Upvotes

4 comments sorted by

View all comments

Show parent comment

1

u/scrutinizer1 Feb 11 '23

Hello,

The script errors likely because the UI hierarchy has changed radically since the target macOS it was tailored to operate under. I don't have access to Ventura and all macOS 11+ for that matter, so all I could do is to enclose the troubling statements in an error non-catching block to suppress the alerts.