我该如何优化此代码?

时间:2015-10-20 20:57:17

标签: excel performance vba

每次,当单元格值(1,2)发生变化时,它将复制该值和单元格(10,19)的值,并将其粘贴到A列和A列中。 B分别 当单元格(1,2)的值发生变化时,我的Excel VBA使Excel挂起:

Dim a As Variant

Dim j As Integer
Dim b As Variant
Dim l As Integer




Private Sub Worksheet_Change(ByVal Target As Range)

If Cells(j + 3, 1).Value = Cells(j + 2, 1).Value Then
          j = j
          Else
          j = j + 1

        End If

  If l < j Then
b = Cells(10, 19).Value
 Cells(j + 1, 2).Value = b

End If
l = j
a = Cells(1, 2).Value
Cells(j + 3, 1).Value = a


End Sub

Private Sub Combobox1_Change()
 Cells(1, 2) = Combobox1.Value

End Sub  

如何防止这种情况发生?

1 个答案:

答案 0 :(得分:0)

首先,您的格式化使其难以阅读 其次,在更改值时不会禁用事件,导致最终的堆栈溢出或内存不足错误,这会降低excel的速度。

格式化和改进的代码:

Dim a 
Dim j As Integer
Dim b 
Dim l As Integer

Private Sub Worksheet_Change(ByVal Target As Range)
If Intersect(Target, "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 Cells(j + 3, 1).Value = Cells(j + 2, 1).Value Then
    j = j
Else
    j = j + 1
End If

If l < j Then
    b = Cells(10, 19).Value
    Cells(j + 1, 2).Value = b
End If

l = j
a = Cells(1, 2).Value
Cells(j + 3, 1).Value = a
Application.EnableEvents = True
End Sub

Private Sub Combobox1_Change()
Cells(1, 2) = Combobox1.Value
End Sub