Excel VBA可以对多个条件求和(500k行)

时间:2018-12-16 08:43:47

标签: excel vba sum

我使用以下代码汇总每月数据 但是由于某些原因,VBA会不停地运行,因此在添加最后一个条件之前,它对我来说还不错。

Sub aqua()
    Dim Markets As Worksheet
    Set Markets = Sheets("sheet4")
    Sheets("DATA").Range("A:A").Name = "list1"
    Sheets("DATA").Range("L:L").Name = "list2"
    Sheets("DATA").Range("M:M").Name = "Printed"
    Sheets("DATA").Range("E:E").Name = "list3"
    Sheets("sheet4").Range("AP:AP").Name = "list4"
    Markets.Range("c1:c20").Name = "MARKET"
    Sheets("DATA").Cells(4, "V") = [sum(if((isnumber(match(list1,market,0)))*(list2>0)*(list1<>"")*(not(isnumber(match(list4,list3,0)))),printed))]
End Sub

1 个答案:

答案 0 :(得分:0)

Excel并不是处理大量数据(例如50万行)的最佳工具

此外,由于您引用的是整个列(例如,“ A:A”,“ L:L”,...)

,因此您实际上正在处理100万行

因此,可能的增强可能是将行数限制为实际的最小行数,如下所示:

Option Explicit

Sub aqua()
    Dim Markets As Worksheet:  Set Markets = Worksheets("Sheet4")
    Dim DATA As Worksheet: Set DATA = Worksheets("DATA")

    Dim list1Rows As Long, list2Rows As Long, list4Rows As Long, printedRows As Long, nRows As Long

    list1Rows = GetLastRowIndex(DATA, "A")
    list2Rows = GetLastRowIndex(DATA, "L")
    printedRows = GetLastRowIndex(DATA, "M")
    list4Rows = GetLastRowIndex(DATA, "AP")
    nRows = WorksheetFunction.Max(list1Rows, list2Rows, list4Rows, printedRows) ' get the actual maximum rows number for "matching" list

    With DATA
        .Range("A1").Resize(nRows).Name = "list1" '
        .Range("L1").Resize(nRows).Name = "list2"
        .Range("M1").Resize(nRows).Name = "Printed"

        .Range("E1").Resize(GetLastRowIndex(DATA, "E")).Name = "list3"
    End With

    With Markets
        .Range("AP1").Resize(nRows).Name = "list4"
        .Range("c1:c20").Name = "MARKET"
    End With


    DATA.Cells(4, "V") = [sum(if((isnumber(match(list1,market,0)))*(list2>0)*(list1<>"")*(not(isnumber(match(list4,list3,0)))),printed))]
End Sub

Function GetLastRowIndex(sht As Worksheet, colName As String) As Long
    With sht
        GetLastRowIndex = .Cells(.Rows.Count, colName).End(xlUp).Row
    End With
End Function

无论如何,50万行是相当大的数据量,您仍然会遇到时间问题