如何优化这段代码,excel挂了一两秒钟怎么办?

当我运行这个代码时,Excel工作簿会挂起一两秒钟…怎么办?

Private Sub Worksheet_Change(ByVal Target As Range) Dim a As Variant Dim b As Variant Dim Number_of_Sims As Integer Number_of_Sims = 76 For i = 3 To Number_of_Sims If Intersect(Target, Range("A:A")) Is Nothing Then Exit Sub 'don't run unless change in column A Application.EnableEvents = False 'stop executing this code until we are done If Len(Range("s10").Value) = 0 Then a = Cells(i, 23).Value Cells(9, 19).Value = a b = Cells(16, 19).Value Cells(i, 24).Value = b End If Next Application.EnableEvents = True End Sub 

首先,你需要释放不依赖循环的东西的循环:

 Application.EnableEvents = False If Intersect(Target, Range("A:A")) Is Nothing Then Exit Sub 

然后你的ab似乎是无用的,所以我只是收集了2行!

所以试试这个应该更有效率:

 Private Sub Worksheet_Change(ByVal Target As Range) If Intersect(Target, Range("A:A")) Is Nothing Then Exit Sub 'don't run unless change in column A With Application .EnableEvents = False 'stop executing this code until we are done .DisplayAlerts = False .ScreenUpdating = False '.Calculation = xlCalculationManual End With Dim Number_of_Sims As Integer Number_of_Sims = 76 If Len(Range("s10").Value) <> 0 Then Else For i = 3 To Number_of_Sims Cells(9, 19).Value = Cells(i, 23).Value Cells(i, 24).Value = Cells(16, 19).Value Next i End If With Application .EnableEvents = True .DisplayAlerts = True .ScreenUpdating = True .Calculation = xlCalculationAutomatic End With End Sub