试试这个
我特意将代码分解为几个 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选择。谢谢你的帮助!!! – Ronald Valdivia 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