使用AppleScript批量替换多个Word文档中的多组文本
解决AppleScript批量替换Word文档文本的报错问题
错误原因
报错Can’t set «class 1650» of missing value to "May 23, 2023"的核心原因是:打开Word文档后未选中任何内容,selection对象为missing value,导致无法访问text object of selection,进而无法设置查找对象的content属性。
修正后的代码
-- Set up the phrases to find and their replacements (ensure proper formatting) set textToFindList to {"May 23, 2023", "Aboriginal Day", "June 21", "2023"} set textReplaceWithList to {"May 24, 2024", "National Indigenous Peoples Day", "June 20", "2024"} -- Ensure the lists are the same length if (length of textToFindList) ≠ (length of textReplaceWithList) then display dialog "Error: Find and Replace lists must be the same length!" return end if -- Choose the folder containing the Word documents set folderPath to POSIX file "/Users/stirlingtait/Documents/Donation Letters" as alias tell application "Finder" -- Look for both .docx and .doc files set fileList to every file of folder folderPath whose name extension is in {"doc", "docx"} end tell tell application "Microsoft Word" activate repeat with fileRef in fileList try open fileRef set doc to active document repeat with i from 1 to length of textToFindList set oldPhrase to item i of textToFindList set newPhrase to item i of textReplaceWithList -- Use the document's text object directly instead of selection set findObject to find object of text object of doc tell findObject clear formatting set content to oldPhrase set replacement text to newPhrase set forward to true set wrap to find stop execute replace all with match case -- Replace all occurrences end tell end repeat save doc close doc saving no on error errMsg number errNum display dialog "Error processing file " & name of fileRef & ": " & errMsg & " (" & errNum & ")" close front document saving no end try end repeat end tell display dialog "Replacement complete!"
关键修改点
- 替换查找对象的来源:将
find object of text object of selection改为find object of text object of doc,直接针对整个文档的文本进行操作,避免依赖选区。 - 完善文件扩展名匹配:在Finder的筛选条件中添加
"docx",确保包含新版Word文档格式。 - 添加错误处理:用
try...on error块捕获单个文件处理时的异常,避免一个文件出错导致整个脚本终止。 - 优化文档关闭逻辑:明确指定
close doc saving no(已执行save操作),避免弹出冗余保存提示。 - 补充长度不匹配提示:当查找和替换列表长度不一致时,弹出明确错误提示,而非直接终止脚本。
内容的提问来源于stack exchange,提问作者Stirling Tait
相关产品推荐
相关产品推荐

