excel - 行插入在循环内很慢
问题描述
我需要在工作表中插入行。
我必须根据某些条件插入大约 350 行,大约需要 30-40 分钟。
下面是我的 VBA 代码:
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
Application.EnableEvents = False
ActiveSheet.DisplayPageBreaks = False
For index = CardetailInfoStartRow To (CardetailInfoStartRow + CardetailRecordCount - 1)
If IsError(CardetailDistance) = False Then
If Len(Trim(CardetailDistance)) > 0 Then
Sheets("Cars").Rows(rowIndexToInsert).Insert Shift:=xlDown
Sheets("Cars").Range("B" & rowIndexToInsert & ":EA" & _
rowIndexToInsert).Value = "Cardetail " & _
Sheets("Cars").Range("I" & index).Value & ", " & CardetailDistance
Sheets("Cars").Range("B" & rowIndexToInsert & ":EA" & rowIndexToInsert).Select
With Selection
.VerticalAlignment = xlTop
.WrapText = True
.Orientation = 0
.AddIndent = False
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = True
.RowHeight = 23
End With
rowIndexToInsert = rowIndexToInsert + 1
End If
End If
Next index
该工作表包含一些条件格式的单元格。
通过一些解决方案,有这个解决方案可以禁用条件格式。我尝试使用 VBA,但性能仍然没有提高。下面的代码是在方法执行之前插入的。
Range("F1:EA" & Range("car_count").Value - 1).Select
Selection.Interior.ColorIndex = xlNone
Selection.Cells.FormatConditions.Delete
是否有任何替代方法可以提高性能?
解决方案
根据评论,我能够为此实施解决方案。不是逐个插入行,而是通过计算需要插入的行数来完成单个插入。现在执行不到一分钟
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
Application.EnableEvents = False
ActiveSheet.DisplayPageBreaks = False
If CarDetailInfoStartRow > 0 And CarDetailRecordCount > 0 Then
Dim recCount As Integer
recCount = 0
For index = CarDetailInfoStartRow To (CarDetailInfoStartRow + CarDetailRecordCount - 1)
CarDetailSplitLimit = Sheets("Cars").Range("BF" & index).Value
If IsError(CarDetailSplitLimit) = False And Len(Trim(CarDetailSplitLimit)) > 0 Then
recCount = recCount + 1
End If
Next index
If recCount > 0 Then
Sheets("Cars").Rows(rowIndexToInsert).EntireRow.Offset(1).Resize(recCount).Insert Shift:=xlDown
End If
For index = CardetailInfoStartRow To (CardetailInfoStartRow + CardetailRecordCount - 1)
If IsError(CardetailDistance) = False Then
If Len(Trim(CardetailDistance)) > 0 Then
Sheets("Cars").Rows(rowIndexToInsert).Insert Shift:=xlDown
Sheets("Cars").Range("B" & rowIndexToInsert & ":EA" & rowIndexToInsert).Value = "Cardetail " & Sheets("Cars").Range("I" & index).Value & ", " & CardetailDistance
Sheets("Cars").Range("B" & rowIndexToInsert & ":EA" & rowIndexToInsert).Select
With Selection
.VerticalAlignment = xlTop
.WrapText = True
.Orientation = 0
.AddIndent = False
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = True
.RowHeight = 23
End With
rowIndexToInsert = rowIndexToInsert + 1
End If
End If
Next index
推荐阅读
- java - 如何在本地“运行”包含多个 EAR 和 WAR 文件的应用程序?
- java - SpringBoot / Java:如何计算项目并在对象映射中获取结果
>> - sql - 自动化归因队列
- android - 停止按钮不适用于 Android Studio 中的颤振
- autodesk-forge - 默认创建后是否有选择标记的方法
- r - 如何将图例放在热图底部,仍未解决?
- arrays - 数组检查对象键是否具有相同的值
- r - 强调.strong.rows (pander) 失败
- javascript - 添加/删除下拉菜单 + 取决于所选下拉菜单的所选插件
- excel - 如何在 Excel 中将“-”更改为空白?