我试图想出最快的方法来在 Excel 中对一个大约有 . 110'000 行。我想出了三种方法,但没有一种是令人满意的。
这是我尝试的第一个:PC 上的执行时间 100 秒!
Sub Test1_WorksheetFunction()
Dim MaxRow As Long, MaxCol As Long
Dim i As Long
Dim StartTimer, EndTimer, UsedTime
StartTimer = Now()
With wsTest
MaxRow = .UsedRange.Rows.Count
MaxCol = .UsedRange.Columns.Count
For i = 2 To MaxRow
.Cells(i, 4) = WorksheetFunction.SumIf(wsData.Range("G2:G108840"), .Cells(i, 1), wsData.Range("R2:R108840"))
Next i
End With
EndTimer = Now()
MsgBox (DateDiff("s", StartTimer, EndTimer))
End Sub
这是第二种方法:执行时间在 55 秒时稍好一些
Sub Test2_Formula_and_Copy()
Dim MaxRow As Long, MaxCol As Long
Dim i As Long
Dim StartTimer, EndTimer, UsedTime
StartTimer = Now()
With wsTest
MaxRow = .UsedRange.Rows.Count
MaxCol = .UsedRange.Columns.Count
Range("D2").Select
ActiveCell.FormulaR1C1 = _
"=SUMIF(Tabelle1[KUNDENBESTELLNR],Test!RC[-3],Tabelle1[ANZAHL NACHFRAGE])"
Range("D2").Select
Selection.AutoFill Destination:=Range("D2:D6285")
Range("D2:D6285").Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
End With
EndTimer = Now()
MsgBox (DateDiff("s", StartTimer, EndTimer))
End Sub
第三次尝试:执行太慢了,它从未完成。
Sub Test3_Read_in_Array()
Dim MaxRow As Long, MaxCol As Long
Dim SearchRange() As String, SumRange() As Long
Dim i As Long, j As Long, k
Dim StartTimer, EndTimer, UsedTime
Dim TempValue
StartTimer = Now()
With wsData
MaxRow = .UsedRange.Rows.Count
ReDim SearchRange(1 To MaxRow)
ReDim SumRange(1 To MaxRow)
For i = 1 To MaxRow
SearchRange(i) = .Range("G" & (1 + i)).Value
SumRange(i) = .Range("R" & (1 + i)).Value
Next i
End With
With wsTest
MaxRow = .UsedRange.Rows.Count
For i = 2 To MaxRow
For j = LBound(SearchRange) To UBound(SearchRange)
k = .Cells(i, 1).Value
If k = SearchRange(j) Then
TempValue = TempValue + SumRange(j)
End If
Next j
.Cells(i, 4) = TempValue
Next i
End With
EndTimer = Now()
MsgBox (DateDiff("s", StartTimer, EndTimer))
End Sub
显然我还没有掌握 VBA(或任何其他编程语言)。有人可以帮助我提高效率吗?一定有办法!对?
谢谢!