使用Applescript在Excel中删除行

我想在使用苹果脚本的Excel中删除特定的行。 我想根据给定列中的值删除行。 在给定的列中,我有一个我想要保留的值列表(例如3001,3004,5003等)。

例如,如果我的任何值(3001,3004,5003)在列CI中都想保留包含该值的行。 如果该行不包含我列中的某个值,则想要删除该行。 我在这里find了这个applescript,但它所做的只是删除了第2行中的所有内容,我无法得到它来保留我的值范围。

因为我正在处理C列,所以我将字段10replace为字段3,并且将“(不是NY状态)”改为“(不是3001)”,但是这并不起作用。 另外我该如何列出这些值,我列出它们是“(3001,3004,5003)”还是“(3001; 3004; 5003)”还是什么?

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 

我只是遍历看着值的行:

 set myValues to {3001, 3004, 5003} tell application "Microsoft Excel" tell active workbook (* Code to count the amount of rows *) repeat with i from rowCount to 1 by -1 set cellValue to value of cell ("C" & i) if cellValue is not in myValues then delete row i end if end repeat end tell end tell 

请注意,它通过行向后迭代。 当你删除一行时,Excel会将行向上移动。 向后退保证每一行都被处理。

根据评论编辑:

为了获得更好的性能,请尝试获取列中的所有值,并循环遍历这些值,而不是在每次迭代期间从Excel中获取单元格值。

 set columnValues to my quickExcelList("C1:C" & rowCount, return) repeat with i from rowCount to 2 by -1 if item i of columnValues is not in myValues then tell application "Microsoft Excel" delete row i end tell end if end repeat --Shane Stanley's routine to get tab/return delimited text from an Excel sheet -------------------------------------------------------------------------------- on quickExcelList(theRange, theDelim) tell application "Microsoft Excel" tell active sheet copy range range theRange set copiedText to the clipboard end tell end tell set theList to strLib's explode(copiedText, theDelim) return theList end quickExcelList