我有三个细胞,这些细胞以下列方式相互依赖:
如果我知道其中两个的值,那么我可以计算剩下的值。换句话说,如果我的三个单元格是A1,A2,A3,
我的目标是获取执行以下操作的工作表:
如果只有两个单元格,那么我会知道如何使用Worksheet.Change
来获得类似的东西。同样,如果两个单元格中的值同时更改,那么我也知道如何获得令人满意的东西。
但是,在我的情况下,更改是连续的而不是同步的,因此我不知道如何实现它,因为Worksheet.Change
仅适用于一个目标。
答案 0 :(得分:4)
您只需跟踪三个单元格的更改状态,并在两个单元格发生更改时执行操作,例如
Private Sub Worksheet_Change(ByVal Target As Range)
Static TrackChange As Integer
On Error GoTo EH
If Not Application.Intersect(Target, Me.Cells(1, 1)) Is Nothing Then
TrackChange = TrackChange Or 1 ' Set bit 0
End If
If Not Application.Intersect(Target, Me.Cells(2, 1)) Is Nothing Then
TrackChange = TrackChange Or 2 ' Set bit 1
End If
If Not Application.Intersect(Target, Me.Cells(3, 1)) Is Nothing Then
TrackChange = TrackChange Or 4 ' Set bit 2
End If
Debug.Print TrackChange
Select Case TrackChange
Case 3 ' A1, A2 changed
Application.EnableEvents = False
' update A3
Me.Cells(3, 1) = Me.Cells(1, 1) + Me.Cells(2, 1)
TrackChange = 0
Case 5 ' A1, A3 changed
Application.EnableEvents = False
' update A2
Me.Cells(2, 1) = Me.Cells(1, 1) + Me.Cells(3, 1)
TrackChange = 0
Case 6 ' A2, A3 changed
Application.EnableEvents = False
' update A1
Me.Cells(1, 1) = Me.Cells(2, 1) + Me.Cells(3, 1)
TrackChange = 0
Case 7 ' A1, A2, A3 changed
TrackChange = 0
End Select
EH:
Application.EnableEvents = True
End Sub