2015-10-20 152 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定義爲變體,則代碼爲我工作,非常感謝先生及時回覆。 –