Infinite loop when using worksheet_change to update a cell based on the color of a different cell

时间:2019-01-07 13:19:56

标签: excel vba

I've been testing a sample to update the value of one cell based off of the color of a different cell. When using worksheet_change to do this excel stops responding. The code for this is below:

 Private Sub Worksheet_Change (ByVal Target As Range)

 Dim c4 As Integer
 C4 = 16
 Cells(1, 4).Value = c4

 If Cells(1, 1).Interior.ColorIndex <> xlColorIndexNone Then
      Cells(1, 4).Value = c4 - 6
 End If

 End Sub

When trying the same thing (and a similar code as shown below) using a command button instead it works fine.

Private Sub CommandButton1_Click()

Dim c4 As Integer
c4 = 16
Cells(1, 4).Value = c4

If Cells(1, 1).Interior.ColorIndex <> xlColorIndexNone Then
    c4 = c4 - 6
End If

Cells(1, 4).Value = c4

End Sub

For this test I changed the color of cell A1 then either clicked the command button or wrote something in a different cell and clicked enter. My question is what can be changed with the worksheet_change version to stop it after it finishes the calculations? Does Exit Sub interact differently with worksheet_change subs than it does manually created subs? Will using Exit Sub still allow the worksheet to be updated on the next change?

0 个答案:

没有答案