2015-10-20 208 views
-2

每当单元格值(1,2)发生更改时,它会将该值和单元格的值(10,19)分别粘贴到列A & B中 我的Excel VBA使Excel在单元格的值1,2)变化:如何优化此代码?

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 

我该如何防止这种情况发生?

+0

什么是'j'应该是什么?每次你改变一个单元格的值时,代码都在踢。而且它会不停地踢,因为你正在改变代码中的单元格值。 – Davesexcel

+1

这是更好放在codereview http://codereview.stackexchange.com/ –

+0

这可能会更好地作为一个从combobox1_change调用的子。在所有期望的单元格中放入一个循环。 –

回答

0

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

格式化,并提高代码:

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 
+0

如果相交(目标,“A:A”)如果相交(目标,范围(“A:A”))并且将昏暗的a&b定义为变体,则代码为我工作,非常感谢先生及时回复。 –