Search code examples
excellistapplescript

Applescript Excel: Using String From List To Use Worksheet


I'm trying to make a simple script for email automation, it's going to get emails from different Excel sheets in the same workbook. I've made a list of the sheet names I want to use, and want to create a prompt with 'choose from list' to create a variable, and use it when creating emails. However, whenever I use the script, Excel only gets data from the active sheet, and disregards my assigned variable for the sheet name. Here's my code snippet:

set LanguageList to {"Albanian", "Bosnian", "Bulgarian", "Croatian", "Czech", "Danish", "Dutch", "Finnish", "Hungarian", "Norwegian", "Polish", "Portugese", "Romanian", "Serbian", "Slovak", "Slovenian", "Spanish", "Swedish"}

set LanguageSheet to choose from list LanguageList with prompt "Select a language:"
activate object sheet LanguageSheet
if LanguageSheet = false then
    error number -128
    --quit workbook EmailList
end if

I added the activate object sheet LanguageSheet to test what's going on, and here's the error Script Editor throws at me in the terminal:

error "Microsoft Excel got an error: The object you are trying to access does not exist" number -1728 from sheet {"Bosnian"}

I guess I can create a long list of if's and use it to refer to the sheet index, while that may work as a solution, I don't understand why this doesn't work. Is there a flaw in my logic?

Thanks for reading.


Solution

  • The choose from list command returns a list, for example:

    --> {"Bosnian"}
    

    The activate object worksheet will not work with a list so you would need to change it to `get item 1 of list, like so:

    set LanguageList to {"Albanian", "Bosnian", "Croatian", "Danish"}
    set LanguageSheet to choose from list LanguageList with prompt "Select a language:"
            
    activate object worksheet (get item 1 of LanguageSheet)
    
    --> "Bosnian"
    

    Alternatively, you can relocate the 'get item 1' to the 'set LanguageSheet' command, which simplifies the 'activate object worksheet' command.

        set LanguageList to {"Albanian", "Bosnian", "Croatian", "Danish"}
        set LanguageSheet to item 1 of (get choose from list LanguageList with prompt "Select a language:")
        activate object worksheet LanguageSheet