如何优化特定的vba代码速度?

我们使用这个VBA代码主要是为了隐藏空白行和取消隐藏非空白行,然后第二个代码在工作表激活后按行定义一个列值。 这个过程需要花费太多的时间用这个代码,任何人都可以帮助我优化这个代码,并使其更快? (工作表包含平均500行)。

Private Sub Worksheet_Activate() HideRows Sortingrisk End Sub Sub HideRows() Dim rRange As Range, rCell As Range Dim strVal As String Set rRange = Worksheets(12).Range("A10:A500") For Each rCell In rRange strVal = rCell rCell.EntireRow.Hidden = strVal = vbNullString Next rCell End Sub Sub Sortingrisk() ActiveWorkbook.Worksheets("Control Implementation Plan").AutoFilter.Sort. _ SortFields.Clear ActiveWorkbook.Worksheets("Control Implementation Plan").AutoFilter.Sort. _ SortFields.Add Key:=Range("G10:G1000"), SortOn:=xlSortOnValues, Order:= _ xlDescending, DataOption:=xlSortNormal With ActiveWorkbook.Worksheets("Control Implementation Plan").AutoFilter.Sort .Header = xlYes .MatchCase = False .Orientation = xlTopToBottom .SortMethod = xlPinYin .Apply End With End Sub 

在你的Sub的开头插入这个:

 Application.ScreenUpdating = False Application.DisplayStatusBar = False Application.Calculation = xlCalculationManual Application.EnableEvents = False 

而这之前End Sub

 Application.ScreenUpdating = True Application.DisplayStatusBar = True Application.Calculation = xlCalculationAutomatic Application.EnableEvents = True 

尝试这个:

 Worksheets(12).Range("A10:A500").SpecialCells(xlCellTypeBlanks).EntireRow.Hidden = True 

你隐藏的行道永恒。 尝试

 Sub HideRows() Worksheets(12).Range("A10:A500").Hidden = True End Sub 

从编程的angular度来看,你应该隐藏你的整个范围而不使用循环。 您还可以优化运行时环境,应用程序属性是第一个启动的地方。

平时

 Application.ScreenUpdating = False 

是加速处理电子表格内容的macros的最重要的一行。

其次是

 Application.Calculation = xlCalculationManual 

如果您的macros触发重新计算,这可能是有用的。 我总是毫不犹豫地从自动改变计算状态,因为如果macros失败,可能会使您的电子表格处于手动模式,这可能是非常危险的,尤其是如果有其他人不知道macros是否正在使用它。

我不会禁用DisplayStatusBar或EnableEvents。 就速度而言,你的立场非常小,而且function也很宽松。

下面是一个简化的代码示例,使用手动计算状态,可以安全地将其重置为非致命错误。 您可能需要考虑删除手动状态或构build其他error handling。

 Private Sub Worksheet_Activate() Application.ScreenUpdating = False HideRows Me SortingRisk Range("G10:G1000") End Sub Sub HideRows(ByRef w As Worksheet) w.Range("A10:A500").Rows.Hidden = True End Sub Sub SortingRisk2(ByRef R As Range) Application.Calculation = xlCalculationManual On Error GoTo term Dim F As AutoFilter With R.Worksheet If .AutoFilter Is Nothing Then R.AutoFilter End If Set F = R.Worksheet.AutoFilter F.Sort.SortFields.Clear End With With F.Sort .SortFields.Add _ Key:=R, _ SortOn:=xlSortOnValues, _ Order:=xlDescending, _ DataOption:=xlSortNormal .Header = xlYes .MatchCase = False .Orientation = xlTopToBottom .SortMethod = xlPinYin .Apply End With term: Application.Calculation = xlAutomatic If Err > 0 Then MsgBox "Error: Macro has terminated. Verify that Workbook Calculation state is in auto." End If End Sub