尝试这个
我特意将代码分解为几个 If 语句和重复代码,以便理解透视。例如
Cells(Target.Row, 4) = "Some Calculation" '<~~ TotalCost Changes
Cells(Target.Row, 6) = "Some Calculation" '<~~ Margin$ Changes
Cells(Target.Row, 7) = "Some Calculation" '<~~ Price Changes
请把它们放在一个共同的过程中。
还要注意 和 的Error Handling
使用Application.EnableEvents
。这两个在使用时是必须Worksheet_Change
的。确保在存在递归操作的情况下Application.EnableEvents = False
代码不会进入可能的无限循环。Error Handling
不仅可以处理错误,还可以通过向您显示错误消息然后将其重置Application.EnableEvents
为True
并最终优雅地退出代码来阻止代码分解。
代码
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
On Error GoTo Whoa
Application.EnableEvents = False
If Not Intersect(Target, Columns(1)) Is Nothing Then '<~~ When Cost 1 Changes
Cells(Target.Row, 4) = "Some Calculation" '<~~ TotalCost Changes
Cells(Target.Row, 6) = "Some Calculation" '<~~ Margin$ Changes
Cells(Target.Row, 7) = "Some Calculation" '<~~ Price Changes
ElseIf Not Intersect(Target, Columns(2)) Is Nothing Then '<~~ When Cost 2 Changes
Cells(Target.Row, 4) = "Some Calculation" '<~~ TotalCost Changes
Cells(Target.Row, 6) = "Some Calculation" '<~~ Margin$ Changes
Cells(Target.Row, 7) = "Some Calculation" '<~~ Price Changes
ElseIf Not Intersect(Target, Columns(3)) Is Nothing Then '<~~ When Cost 3 Changes
Cells(Target.Row, 4) = "Some Calculation" '<~~ TotalCost Changes
Cells(Target.Row, 6) = "Some Calculation" '<~~ Margin$ Changes
Cells(Target.Row, 7) = "Some Calculation" '<~~ Price Changes
ElseIf Not Intersect(Target, Columns(7)) Is Nothing Then '<~~ When Cost Price Changes
Cells(Target.Row, 5) = "Some Calculation" '<~~ Margin% Changes
Cells(Target.Row, 6) = "Some Calculation" '<~~ Margin$ Changes
End If
LetsContinue:
Application.EnableEvents = True
Exit Sub
Whoa:
MsgBox Err.Description
Resume LetsContinue
End Sub
我假设第 1 行受到保护,用户不会改变它。如果标题行不受保护,那么您将检查行号与If
语句以排除第 1 行
跟进
我选择其中一个成本(Cost1 的第一个),执行 Ctrl+C,选择 Cost 3 下的所有单元格并执行 Crl+V,它会复制值,但它只会重新计算第一个单元格的 TotalCost 选择。谢谢你的帮助!!!– 罗纳德·瓦尔迪维亚 24 分钟前
啊,我明白你在尝试什么:)
使用此代码
Private Sub Worksheet_Change(ByVal Target As Range)
Dim cl As Range
On Error GoTo Whoa
Application.EnableEvents = False
If Not Intersect(Target, Columns(1)) Is Nothing Then
For Each cl In Target
Cells(cl.Row, 4) = Cells(cl.Row, 1) + Cells(cl.Row, 2) + Cells(cl.Row, 3)
Next
ElseIf Not Intersect(Target, Columns(2)) Is Nothing Then
For Each cl In Target
Cells(cl.Row, 4) = Cells(cl.Row, 1) + Cells(cl.Row, 2) + Cells(cl.Row, 3)
Next
ElseIf Not Intersect(Target, Columns(3)) Is Nothing Then
For Each cl In Target
Cells(cl.Row, 4) = Cells(cl.Row, 1) + Cells(cl.Row, 2) + Cells(cl.Row, 3)
Next
End If
LetsContinue:
Application.EnableEvents = True
Exit Sub
Whoa:
MsgBox Err.Description
Resume LetsContinue
End Sub