为Excel编写Apple Script,删除单元格中具有特定值的行



我正在尝试删除excel中具有特定值的单元格。我已经走了很长的路,并借用互联网上的一些摘录写了自己的剧本。

set theOutputPath to (path to desktop folder as string) & "FilteredNY.csv"
set fstring to "(Not NY State)"
tell application "Microsoft Excel"
activate
open workbook workbook yatta yatta
activate object worksheet 1
-->activate range current region
set LastRow to ((count of rows of used range of active sheet) + 1)
set lastCol to count of columns of used range of active sheet
set lastCol to (get address of column lastCol without column absolute)
set lastCol to (characters 1 thru ((length of lastCol) div 2) of lastCol as string)
set fullRange to range ("2:" & LastRow)
repeat with i from 2 to LastRow
--code in repeat 
if value of cell ("J" & i) is equal to fstring then
delete range row i
end if
end repeat
end tell

大多数代码都不太重要,包括fullRange变量和顶部设置的路径变量。问题是删除代码甚至在第2行之后都没有进行,而且在这上面运行得非常慢,所以它实际上有很多问题。我想我做的那个循环肯定有问题。如果有人能让我走上正轨,那就太好了。

事实上,我最近在做了很多实验/挖掘后发现了这个问题。当我删除范围时,行实际上移动了excel的前导行,删除了错误的范围。我目前正在制定一个解决方案,包括只清除我不想要的行,隐藏所有空白单元格,然后将所有可见单元格复制到新的工作表中。

好的,又一次更新,最后一次更新。我终于完成了脚本,让它可以做它需要做的事情。我没有进行所有的清除、隐藏和复制,而是通过在数组中添加所有要删除的行来进行删除,而不是将数组转换为一个范围字符串,删除范围可以一次删除所有行。这是一个更快、更简单的解决方案。

这是伟大的苹果脚本:

set theOutputPath to (path to desktop folder as string) & "FilteredNY.csv"
set fstring to "(Not NY State)"
set del_list to {}
tell application "Microsoft Excel"
activate
open workbook workbook file name yatta yatta
activate object worksheet 1
set LastRow to ((count of rows of used range of active sheet))
repeat with i from 2 to LastRow
--code in repeat 
if value of cell ("J" & i) is equal to fstring then
set di to i as string
set end of del_list to di & ":" & di
end if
end repeat
set AppleScript's text item delimiters to ","
set ToDelete to del_list as string
set AppleScript's text item delimiters to {""}
delete range range ToDelete
end tell

我希望这能帮助到外面的人!我有一个解决自己问题的坏习惯。

将Excel与appescription一起使用时,尽量避免循环,并使用Excel强度在短时间内处理大量行/列。

对于您的情况,我理解您希望删除列"J"的值为"(非纽约州)"的所有行你们并没有触摸第一行,那个里必须有你们的列标题。

这是代码:

tell application "Microsoft Excel"
set autofilter mode of active sheet to false
set lastRow to first row index of last row of used range
autofilter range row ("1:" & lastRow) field 10 criteria1 "(Not NY State)"
select row ("2:" & lastRow)
delete selection -- if you want to delete 
#clear contents selection -- if you only wish to clear the data
end tell

这不是更快吗?

加速代码的奖励技巧:

tell application "Microsoft Excel" to set screen updating to false --vvv---
-- insert here operations that would change Excel display --
tell application "Microsoft Excel" to set screen updating to true --^^^---

您也可以使用自动筛选+排序

但真正重要的是在Excel中巧妙地使用公式来快速完成任务。(设置一个单元格的公式,然后填充到最后一行)

最新更新