You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用AppleScript检查Numbers中指定名称工作表是否存在

AppleScript判断Numbers指定名称工作表是否存在的修正方案

错误原因

你原来的写法触发了AppleScript的过滤查询规则:使用whose条件检索对象时,如果没有匹配结果,AppleScript会直接抛出「无法找到对应对象」的错误,而不是返回布尔值的false,所以无法直接用exists搭配whose做存在性判断。

修正后的完整代码

set nextTuesday to current date
repeat until nextTuesday's weekday is Tuesday
    set nextTuesday to nextTuesday + days
end repeat
set {year:nextTuesdaysYear, month:nextTuesdaysMonth, day:nextTuesdaysDay} to nextTuesday
set nextTuesdaysName to "Tuesday " & (nextTuesdaysYear * 10000 + nextTuesdaysMonth * 100 + nextTuesdaysDay as string)

tell application "Numbers"
    tell document 1
        -- 先获取所有工作表的名称列表,检查目标名称是否存在
        set allSheetNames to name of every sheet
        if nextTuesdaysName is in allSheetNames then
            set userChoice to button returned of (display dialog "There's already a worksheet named '" & nextTuesdaysName & "'" buttons {"Quit", "Replace"} default button 2 with icon 1)
            if userChoice is "Quit" then
                return -- 直接退出脚本
            else
                -- 用户选替换就删除旧工作表
                delete sheet nextTuesdaysName
            end if
        end if
        -- 新建工作表
        set thisSheet to make new sheet with properties {name:nextTuesdaysName}
    end tell
end tell

核心修改点说明

  • 把原来的whose存在判断改为先读取所有工作表的名称组成数组,再判断目标名称是否在数组中,全程不会触发找不到对象的错误
  • 补充了对话框选择的处理逻辑:选「Quit」直接终止脚本,选「Replace」先删除原有同名工作表再新建,避免后续新建步骤仍然报错

内容的提问来源于stack exchange,提问作者Russ

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 04:03:02