首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在VBA中优化循环逻辑语句

在VBA中优化循环逻辑语句
EN

Stack Overflow用户
提问于 2018-09-18 17:01:17
回答 2查看 54关注 0票数 0

我写这段代码是为了从表中删除特定列中不包含单词"ITA“、"GRE”或"CHE“的所有行。现在,表很大(60k个观察值),循环显然很耗时(5-6分钟)。为了优化代码的效率,处理任务的另一种方法是什么(例如,在10到30秒内执行任务)?

代码语言:javascript
复制
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
EN

回答 2

Stack Overflow用户

发布于 2018-09-18 17:18:56

通过构建不属于country列中的值数组的键的字典来创建AutoFilter。删除可见的行。

代码语言:javascript
复制
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
票数 2
EN

Stack Overflow用户

发布于 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或搜索。删除从顶部到您刚找到的地址的行

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52382809

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档