首页 > 解决方案 > 遍历列,将每个单元格的内容减去一定数量,并将结果存储在同一个单元格中

问题描述

我正在尝试打开 Pages 文档。但它不允许我打开 Pages 文件,这些文件都是灰色的。我想要做的是遍历第一个表的“C”列的所有单元格,然后从其内容中减去一定数量,当然将结果保存在同一个单元格中。这就是我正在写的内容,但我不确定,因为我昨天开始学习 AppleScript。

  tell application "Pages"
    activate
    try
        set the chosenDocumentFile to ¬
            (choose file of type ¬
                {"com.apple.iwork.pages", ¬
                    "com.microsoft.word.doc", ¬
                    "org.openxmlformats.wordprocessingml.document"} ¬
                    default location (path to documents folder) ¬
                with prompt "Choose the Pages or Microsoft Word document to open:")
        open the chosenDocumentFile
    on error errorMessage number errorNumber
        if errorNumber is not -128 then
            display alert errorNumber message errorMessage
        end if
        
        tell the first table of chosenDocumentFile
            repeat with i from 2 to count of cells of column "C"
                set the value of cell i of column "C" to... #don't know how to subtract an amount and then store the result
            end repeat
        end tell
        
    end try
end tell

标签: applescript

解决方案


事先,在一个单独的脚本中,获取页面文档的类型标识符(我使用的是 v7,不知道它是否有区别)。不知道为什么它是必要的,但获取类型标识符是一个两步过程。本质上,如果没有 sffpages 作为字符串的一部分,您还可以过滤掉所有页面文档。

tell application "Finder"
    set pgsF to ((path to documents folder) & "sam.pages" as text) as alias
    -- or…
    -- set pgsF to (choose file)
    set infor to info for pgsF
    set ti1 to type identifier of infor
    --> "com.apple.iwork.pages.sffpages"        
end tell

我们可以像这样把它放到一个新的applescript中:

set ti1 to "com.apple.iwork.pages.sffpages"
tell application "Pages"
    activate
    set cdf to choose file of type ti1 with prompt ¬
    "Choose the Pages or Microsoft Word document to open:"
    open cdf
    
    tell page 1 of document 1
        
        set cc to column "C" of table 1
        set cColc to cells 2 thru -1 of cc whose value is not missing value
        set cColv to value of cells 2 thru -1 of cc whose value is not missing value
        
        repeat with fc in cColc
            set value of fc to (value of fc) - 2
        end repeat
        
    end tell
end tell

如果“C”列的单元格中总是有一个值,那么您可能会省去“其值不是缺失值”序列。没有任何错误处理,例如,如果“C”列中有非数字数据,则会导致错误。

您可能需要将表格的“对象放置”设置为“停留在页面上”(然后选择表格View > Show Arrange Tools > Object Placement,或从检查器的Arrange选项卡中选择),然后才能在 applescript 中使用表格。如果未设置,您可能会收到如下错误:Pages got an error: Can’t get table 1 of page 1 of document 1. Invalid index.

更新:现在过滤出 1 行标题。通过编辑“2”或“-1”,可以排除更多标题行。


推荐阅读