使用CountIf重复访问电子表格吗?

时间:2016-05-03 16:13:03

标签: excel-vba vba excel

下面的代码片段是否存在内存效率低下的问题?它使Excel似乎永远运行Long2的大值(> 50,000)。它适用于Long2的中小值,但对于较大的值,它不会按比例延长时间,似乎永远不会完成。推送Ctrl-Break仅提供旋转进度轮和无响应,即使我的代码前面有DoEvents来显示进度条。

我一遍又一遍地阅读工作表吗?我的印象是我正在读取记忆中的Range个物品,但如果我错了,请纠正我。

请原谅我的匈牙利符号。

''A' and 'AV' Matches
If boolMatchesSheetExists = True Then
    With ThisWorkbook.Sheets("Matches")
        Long2 = Application.CountA(.Columns(1))
        Set Range2 = .Range(.Cells(1, 1), .Cells(Long2, 1))
        Set Range3 = .Range(.Cells(1, 19), .Cells(Long2, 19))
        Set Range4 = .Range(.Cells(1, 36), .Cells(Long2, 36))
    End With
    For Each Cell1 In Range1
        ''A' Matches
        If Application.CountIfs(Range2, Cell1.Value, Range3, "<>" & Cell1.Value, Range4, "A") > 0 Then
            .Cells(Cell1.Row, 2).Value = 1
        Else
            .Cells(Cell1.Row, 2).Value = 0
        End If
        ''AV' Matches
        If Application.CountIfs(Range2, Cell1.Value, Range3, "<>" & Cell1.Value, Range4, "AV") > 0 Then
            .Cells(Cell1.Row, 3).Value = 1
        Else
            .Cells(Cell1.Row, 3).Value = 0
        End If
        ''A' Claims Duping Against Self
        If Application.CountIfs(Range2, Cell1.Value, Range3, Cell1.Value) > 0 Then
            .Cells(Cell1.Row, 4).Value = 1
        Else
            .Cells(Cell1.Row, 4).Value = 0
        End If
    Next Cell1
End If

编辑:根据@ 200_success的建议,此代码使用布尔结果(0,1)填充摘要表(“摘要”),以确定是否匹配特定类型('A','发现AV','Self-Dup')。如果仔细查看上面的代码,您会发现缺少With块应该包含整个内容 - 实际上,有一个:With ThisWorkbook.Sheets("Summary")

1 个答案:

答案 0 :(得分:1)

使用Range对象时,您正在使用工作表 - CountIfs正在访问工作表,.Cells.Value = 1正在更改工作表。

如果范围非常大,将数据从工作表移动到VBA变量并再次返回,循环等,可能会耗费大量时间。

Chip Pearson讨论了如何快速将数据从Range移动到数组中,反之亦然。在VBA中循环遍历数组非常快。

相关问题