使用VBA提高Excel的性能?

我们有一个单一的公式,我们正在应对超过25万个细胞的确定范围。 Excel的performance显然受到重创。 有没有办法通过使用VBA来提高性能?

公式返回0或1作为一个值的单元格取决于4条件。 Excel的公式是:

=IF(NOT(ISTEXT($B9)),"",IF((L$5=""),"",IF(AND(M$5>MIN($G9,$H9),L$5<MAX($G9,$H9)),1,0))) 

谢谢你的帮助 !

像这样的东西可以替代250,000行的公式。 正如评论所述,鉴于数据集的大小,这仍然需要一些时间。 我用一张表单进行了一个testing,只有249,488行填充了必要的单元,代码需要12秒才能运行。 随着更多的数据,我预计这需要更长的时间。

这就是说,这将会显着减less文件的内存,因为不会有任何公式:

 Sub Run() Dim i As Long 'Row number for loop Dim lRow As Long 'Last row of data set Dim ms As Worksheet Set ms = Sheets("Sheet1") 'Change to whatever sheet you need this in With ms If .Cells(5, 12).Value = "" Then MsgBox "Please enter a value in Cell L5 before proceeding." Else lRow = .Cells(.Rows.Count, 2).End(xlUp).Row 'This is assuming Column B is populated in full to the bottom of the data set For i = 9 To lRow 'This is assuming you will be starting the calculation in row 9 If IsNumeric(.Cells(i, 2).Value) = False And .Cells(i, 2).Value <> "" Then 'Ensuring Column B is text and not blank If .Cells(5, 12).Value < WorksheetFunction.Max(.Cells(i, 7).Value, .Cells(i, 8).Value) And .Cells(5, 13).Value > WorksheetFunction.Min(.Cells(i, 7).Value, .Cells(i, 8).Value) Then .Cells(i, 1).Value = 1 'Assuming you want the 0 or 1 in Column A Else .Cells(i, 1).Value = 0 'Assuming you want the 0 or 1 in Column A End If End If Next i End If End With End Sub 

编辑

根据Cornintern的真棒build议,我已经重写了这个使用数组而不是循环遍历整个范围。 这现在不到2秒钟:

 Sub Run() Dim i As Long 'Row number for loop Dim lRow As Long 'Last row of data set Dim ms As Worksheet Dim mVar1() As Variant Dim mVar2() As Variant Dim mVar3() As Variant Dim rVar() As Variant Dim num1 As Long Dim num2 As Long Set ms = Sheets("Sheet1") 'Change to whatever sheet you need this in With ms If .Cells(5, 12).Value = "" Then MsgBox "Please enter a value in Cell L5 before proceeding." Else lRow = .Cells(.Rows.Count, 2).End(xlUp).Row 'This is assuming Column B is populated in full to the bottom of the data set ReDim rVar(1 To lRow - 8) As Variant mVar1 = .Range("G9:G" & lRow) mVar2 = .Range("H9:H" & lRow) mVar3 = .Range("B9:B" & lRow) num1 = .Cells(5, 12).Value num2 = .Cells(5, 13).Value For i = 1 To UBound(mVar1) 'This is assuming you will be starting the calculation in row 9 If IsNumeric(mVar3(i, 1)) = False And mVar3(i, 1) <> "" Then 'Ensuring Column B is text and not blank If num1 < WorksheetFunction.Max(mVar1(i, 1), mVar2(i, 1)) And num2 > WorksheetFunction.Min(mVar1(i, 1), mVar2(i, 1)) Then rVar(i) = 1 Else rVar(i) = 0 End If End If Next i End If End With Range("A9:A" & lRow) = WorksheetFunction.Transpose(rVar) End Sub 

鉴于你的公式很简单,我期望公式的方法会比VBA计算更快/更好:

  • Excel使用多个核心进行计算:VBA仅使用1
  • 将数据传输到VBA并返回到Excel的开销很大
  • Excel可以计算每秒超过一百万个简单的公式
  • 如果任何数据发生变化,Excel可以自动重新计算,但是您将不得不重新运行整个VBA子。

我build议看看公式方法在实践中需要多长时间:如果计算时间超过一秒,我会感到惊讶。