根据其他单元格更改列值

时间:2019-10-30 20:52:46

标签: excel vba

我想根据另一个列值(如果值更改)更新2列值。假设我的A列具有列表(AA1,AA2,AA3),B列具有列表(BB1,BB2),C列具有列表(CC1,CC2)。如果从A列中选择值“ AA1”,则B列值应更改为BB2,而C列应更改为CC1。但是,如果在A列中选择的值与“ AA1”不同,则什么也不会发生。 B列中的值“ BB1”也发生相同的过程。我添加了一个vba,但是它不起作用。还有没有运行vba代码的另一种方法吗?谢谢

Private Sub Worksheet_Change(ByVal Target As Range)

   Dim changedCells As Range
   Set changedCells = Range("A:C")

   If Not Application.Intersect(changedCells, Range(Target.Address)) Is Nothing Then

      If Target.Count > 1 Then Exit Sub

      If Target.Column = 1 And LCase(Target.Value) = "aa1"Then
            Cells(Target.Row, 2) = "BB2"
            Cells(Target.Row, 3) = "CC1"
      ElseIf Target.Column = 2 And LCase(Target.Value) = "bb1" Then
           Cells(Target.Row, 1) = "AA3"
           Cells(Target.Row, 3) = "CC2"
       ElseIf Target.Column = 3 And LCase(Target.Value) = "cc2" Then
           Cells(Target.Row, 1) = "AA2"
           Cells(Target.Row, 2) = "BB2"
        End If
 End If
End Sub

1 个答案:

答案 0 :(得分:2)

您的代码大致上可以,除了会导致事件级联(更改单元格会触发Worksheet_Change事件,该事件会更改单元格,从而会触发Worksheet_Change,从而...)

您需要添加Application.EnableEvents = False来防止这种情况(最后添加... = True

将您的代码重构为可解决此问题以及其他一些小问题

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim changedCells As Range

    On Error GoTo EH '~~ ensure EnableEvents is turned back on if an error occurs

    Set changedCells = Me.Range("A:C") '~~ explicitly refer to the correct sheet

    If Target.Count > 1 Then Exit Sub '~~ do this first, to speed things up

    If Not Application.Intersect(changedCells, Target) Is Nothing Then '~~ Target is already a range
        Application.EnableEvents = False '~~ prevent an event cascade

        '~~ original If Then Else works fine.  But can be simplified
        Select Case LCase(Target.Value)
            Case "aa1"
                If Target.Column = 1 Then
                    Me.Cells(Target.Row, 2) = "BB2"
                    Me.Cells(Target.Row, 3) = "CC1"
                End If
            Case "bb1"
                If Target.Column = 2 Then
                    Me.Cells(Target.Row, 1) = "AA3"
                    Me.Cells(Target.Row, 3) = "CC2"
                End If
            Case "cc2"
                If Target.Column = 3 Then
                    Me.Cells(Target.Row, 1) = "AA2"
                    Me.Cells(Target.Row, 2) = "BB2"
                End If
        End Select
    End If

'~~ Fall through to EnableEvents
EH:
    Application.EnableEvents = True '~~ ensure EnableEvents is turned back on
End Sub