[英]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.