【问题标题】:How to loop through all rows in Excel using Applescript?如何使用 Applescript 遍历 Excel 中的所有行?
【发布时间】:2011-10-27 01:45:19
【问题描述】:

我正在尝试遍历 Excel 中的所有行并在每一行上运行一些命令,但我不知道怎么做!

我最初尝试在 rb-appscript(AppleScript 的 Ruby 包装器)中执行此操作,但我决定在添加另一个 DSL 之前先尝试使其在 Applescript 中运行会更好。有小费吗? (rb-appscript 版本也不错,虽然不是必需的)。

谢谢!

【问题讨论】:

    标签: ruby excel applescript rb-appscript


    【解决方案1】:

    范围的坐标是一个可以动态创建的字符串。循环遍历行的最简单方法是这样的:

    repeat with thisRow from 1 to 10
        tell application "Microsoft Excel"
            set theRange to "A:" & thisRow & "Z:" & thisRow
            set theValue to (get value of range theRange) as list
            -- do something with the row's data
        end tell
    end repeat
    

    每 cmets 更新: 为了获得需要计算的行数,我在很久以前编写了一个子例程来帮助解决这个问题。确保您有某种始终填充的“关键”列(换句话说,没有跳过的单元格)。这目前考虑了标题行,因为我所有的电子表格都有它们:

    on GetItemCount(KeyColumn)
        set RowNumber to 1
        set theText to "cSyoyodylg" -- dummy value
        tell application "Microsoft Excel"
            repeat until theText is ""
                set RowNumber to RowNumber + 1
                set theRange to KeyColumn & RowNumber & ":" & KeyColumn & RowNumber
                set dataRange to range theRange of sheet 1
                set theText to (get value of range theRange)
            end repeat
        end tell
        set rowCount to RowNumber - 1
        return rowCount
    end GetItemCount
    

    要使用,只需这样做: 将 lastRow 设置为我的 GetItemCount("A")

    repeat with thisRow from 2 to lastRow + 1
        -- go attack Excel
    end repeat
    

    【讨论】:

    • 同时,我认为在深入研究 rb-appscript 之前,您需要花一些时间使用 Applescript,因为我认为它的翻译效果不是很好。
    • 谢谢!虽然我看到这循环了 10 行——我希望循环遍历所有行。关于如何实现这一目标的任何想法?我同意你的评论,尽管 rb-appscript 的人发布了这个名为 ASTranslate 的漂亮小工具,可以将 AppleScript 转换为 AppScript(Ruby、Python 或 Objective C)。可以在这里找到:sourceforge.net/projects/appscript/files
    • @yuval:我已经根据您的 cmets 更新了我的答案,因为无法将答案作为评论来回答。我仍然建议花一些时间在 Applescript 上,以了解 rb-appscript 项目的背景和意图。
    • 这在 Excel 2016 中似乎不再起作用 - 它似乎不喜欢 Range 的格式。
    猜你喜欢
    • 2021-05-23
    • 1970-01-01
    • 2012-09-26
    • 1970-01-01
    • 2018-07-23
    • 1970-01-01
    • 2021-02-25
    • 1970-01-01
    • 2015-05-18
    相关资源
    最近更新 更多