繁体   English   中英

根据另一个单元格更改列值

[英]Change columns value based on another cell

我想根据另一个列值更新 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

您的代码大致可以,除了它会导致事件级联(更改单元格会触发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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM