【问题标题】:Optimize loop logical statement in VBA [duplicate]优化VBA中的循环逻辑语句[重复]
【发布时间】:2018-09-18 09:01:17
【问题描述】:

我编写此代码是为了从表中删除特定列中不包含单词“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

【问题讨论】:

  • 工作表的名称是什么?
  • 设置 sht=Sheets("All")
  • 供将来参考:这是找出损坏代码不起作用的地方。需要改进的功能代码(例如更短的运行时间)更适合Code Review

标签: vba excel


【解决方案1】:

通过构建不属于国家列中的值数组的键的字典来创建自动过滤器。删除可见行。

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

【讨论】:

  • 谢谢。我试过了,但是当我运行宏时,我得到类型不匹配错误(当我使用 F8 时我没有得到错误)。我尝试更改变量 dim 但似乎不起作用...
  • 您没有看到我在初次发布后所做的小修改。
  • 仍然得到错误类型不匹配。试图改变暗淡,但它不起作用。而且,此外,它不允许我调试以查看问题可能出在哪里
  • 为我工作。我猜我编的样本数据和你的不一样。别担心,我想我可以为我们俩节省一些时间。
【解决方案2】:

我会让它变得简单(手动或 VBA): 1)使用公式向表中添加 1 个临时列,以检查是否应删除该行,例如"=IF(OR(country="ITA";country="CHE";country="GRE"); "let";"delete")。临时列将显示以下两个值之一:"delete"、"let ”。之后,您可以将公式更改为值,以使过程更快 2) 使用 temp 列对表 A-Z 进行排序 3) 以任何方式搜索要删除的最后一行,例如使用 countif 或搜索。删除从顶部到您刚刚找到的地址的行

【讨论】:

    猜你喜欢
    • 2020-02-06
    • 2012-03-25
    • 1970-01-01
    • 2016-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-15
    • 1970-01-01
    相关资源
    最近更新 更多