我正在尝试使用applescript删除excel中的特定行。我想根据给定列中的值删除行。在给定的列中,我有一个我想保留的值列表(例如3001,3004,5003等)。
例如,如果我的任何值(3001,3004,5003)在C列中,我想保留包含该值的行。如果该行不包含C列中的某个值,我想删除该行。我在这里发现了这个AppleScript,但它所做的就是删除除了第2行之外的所有内容,我无法保留我的值范围。
我将字段10替换为字段3,因为我使用的是C列,然后我将“(不是纽约州)”更改为“(不是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
答案 0 :(得分:1)
我只是遍历查看值的行:
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