如何使用AppleScript引用命名的Excel列?

时间:2014-08-17 19:31:23

标签: excel applescript applescript-excel

想象一下,您有一个名为Customers.xlsx的Excel 2010电子表格(如果您尝试,这很容易)。

您有一个名为Customers的工作表。

电子表格数据如下所示:

CustomerId  Name      Email
----------  --------  ---------------
1001        Ken       ken@gmail.com
2001        Jennifer  jen@gmail.com
3001        Violet    violet@gmail.com

我有一个简单的AppleScript,它只是遍历这些数据并显示每行的对话框。

set strExcelFileLocation to "Macintosh HD:Users:lowken:Documets:ExcelTest:Customers.xlsx"
set strWorkSheetName to "Customers"
set intCnt to 2
set intCustomerIdIndex to 1
set intNameIndex to 2
set intEmailIndex to 3

tell application "Microsoft Excel"
    activate
    --open workbook workbook file name strExcelFileLocation
    activate object worksheet strWorkSheetName

    set intLastRow to first row index of (get end (last cell of column 1) direction toward the top)

    tell active sheet to set myData to value of used range
    repeat
        set intCustomerId to item {intCustomerIdIndex} of item {intCnt} of myData
        set strEmail to item {intEmailIndex} of item {intCnt} of myData
        set strName to item {intNameIndex} of item {intCnt} of myData

        display dialog "Customer " & intCustomerId & " " & strName & " has an email address of " & strEmail 

        if intCnt = intLastRow then
            exit repeat
        end if
        set intCnt to (intCnt + 1)      
    end repeat  
end tell

除了我有一个问题,一切都很好。我使用整数索引值来引用列。所以我使用3来引用电子邮件列。

当我想将电子邮件移至第4列时会发生什么?就目前而言,我的AppleScript会破产。

您可以命名Excel列。这是通过突出显示列(列" C"用于电子邮件)并为列添加名称来完成的。在这个例子中,Column" C"将是"电子邮件"。

我被困在我的AppleScript中使用列名。

我尝试进行以下更改,但它没有工作......

set strEmail to item {"Email"} of item {intCnt} of myData

是否可以通过列名检索列索引?

这样的事情:

set intEmailIndex to IndexOfExcelColumn("Email")

有人可以告诉我如何在Excel中使用列名。我的最终目标是能够在电子表格中间添加新列而不会破坏AppleScript。

由于

1 个答案:

答案 0 :(得分:1)

我建议根据我的评论,最简单的解决方案是在脚本的开头循环遍历列并捕获每个标题的索引,然后您可以继续在其余部分中使用这些索引的剧本。