我编写了这段代码,以便从表中删除特定列中所有不包含单词“ ITA”,“ GRE”或“ CHE”的行。现在,表很大(观察到60k),循环显然很耗时(5-6分钟)。处理任务以优化代码效率(即在10到30秒内执行任务)的另一种方式是什么?
Sub test()
countrycol = UsedRange.Find("Country", lookat:=xlWhole).Column
For j = 1 To Cells(Rows.Count, countrycol).End(xlUp).Row
If UsedRange.Cells(j + 1, countrycol).Value <> "ITA" Or UsedRange.Cells(j + 1, countrycol).Value <> "GRE" _
Or UsedRange.Cells(j + 1, countrycol).Value <> "CHE" Then
UsedRange.Cells(j + 1, countrycol).EntireRow.Delete
End If
Next j
End Sub
答案 0 :(得分:2)
通过构建不属于country列值数组的键的字典来创建自动筛选器。删除可见行。
sub test2()
dim i as long, arr as variant, m as variant, dict as object
set dict = createobject("scripting.dictionary")
with worksheets("All")
if .autofiltermode then .autofiltermode = false
m = application.match("country", .rows(1), 0)
if iserror(m) then exit sub
arr = .range(.cells(2, m), .cells(.rows.count, m).end(xlup)).value2
for i = lbound(arr, 1) to ubound(arr, 1)
select case ucase(arr(i, 1))
case "ITA", "GRE", "CHE"
'do nothing
case else
dict.item(arr(i, 1)) = arr(i, 1)
end select
next i
with .cells(1, 1).currentregion
.autofilter field:=m, criteria1:=dict.keys, operator:=xlfiltervalues
with .resize(.rows.count-1, .columns.count).offset(1, 0)
if cbool(application.subtotal(103, .cells)) then
.specialcells(xlcelltypevisible).entirerow.delete
end if
end with
end with
.autofiltermode = false
end with
end sub
答案 1 :(得分:1)
我将使其变得简单(手动或VBA): 1)使用公式向表中添加1个临时列,以检查是否应删除该行,例如“ = IF(OR(country =” ITA“; country =” CHE“; country =” GRE“);” let“;” delete“)。temp列将显示以下两个值之一:” delete“,” let “。之后,您可以将公式更改为值,以使过程更快 2)使用临时列对表A-Z进行排序 3)以任何方式搜索要删除的最后一行,例如使用countif或搜索。从顶部删除行到您刚刚找到的地址