发生这种情况是因为您的程序工作非常繁忙。例如,您Sub TheLoop()
正在访问 20995 x 16 次单元格以在其上写入字符串。VBA 与 Excel 的交互很慢。
你可以做几件事来加快这个过程。
1.在运行程序之前禁用事件处理程序、屏幕更新和计算。在程序结束时再次恢复设置。
'Disable'
Application.EnableEvents = False
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
'...... Code'
'Enable'
Application.EnableEvents = True
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
2.可以优化Sub TheLoop
。不要立即在单元格上写入,而是将值写入数组中。数组充满值后,将数组的值分配给您需要的范围。例如:
Dim ResultValues() As String
Dim j As Long
ReDim ResultValues(2 To 20997, 1 To 3)
For j = 2 To 20997
ResultValues(j, 1) = "New Defect"
ResultValues(j, 2) = "3"
ResultValues(j, 3) = "2"
Next j
With ThisWorkbook.Worksheets("myWorksheet")
.Range(.Cells(2, 3), .Cells(20997, 5)) = ResultValues
End With
编辑:
鉴于您修改的列之间的列只是文本或空单元格,您可以:
- 将整个范围读入一个数组。
- 然后以与当前修改单元格相同的方式修改数组。
- 修改完成后,再次将整个矩阵转储到范围内。
例如:
Sub TheLoop()
Dim arrRangeValues() as Variant
Dim j as Long
arrRangeValues= Range("A2:V20997").Value2
For j = 2 To 20997
arrRangeValues(j, 1) = "Defect" 'Cells(row_index , column_index)'
arrRangeValues(j, 3) = "New Defect"
arrRangeValues(j, 4) = "3" ' this one also might be empty'
arrRangeValues(j, 5) = "2" ' this one also might be empty'
arrRangeValues(j, 7) = "Name Surname"
arrRangeValues(j, 8) = arrRangeValues(j, 7)
arrRangeValues(j, 16) = arrRangeValues(j, 7)
...
arrRangeValues(j, 10) = " http://SERVER_NAME:8888/PROJECT_NAME/ "
Next j
Range("A2:V20997").Value2 = arrRangeValues
End Sub