我写这段代码是为了从表中删除特定列中不包含单词"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发布于 2018-09-18 17:18:56
通过构建不属于country列中的值数组的键的字典来创建AutoFilter。删除可见的行。
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发布于 2018-09-18 17:44:22
我会让它变得简单(手动或VBA):1)使用公式向表中添加1个临时列,以检查行是否应该删除,例如"=IF(OR(country="ITA";country="CHE";country="GRE");"let";"delete")。temp列将显示以下两个值之一:"delete“、"let”。在此之后,您可以将公式转换为值以使过程更快2)使用临时列对表格A-Z进行排序3)以任何方式搜索要删除的最后一行,e.g.using countif或搜索。删除从顶部到您刚找到的地址的行
https://stackoverflow.com/questions/52382809
复制相似问题