更新5个值来总计一个特定的数字

我有一个数据集,看起来如下,应该始终等于100:

在这里输入图像说明

如果我更改了其中一个值,我希望将它旁边的值调整为总数仍然为100.不幸的是,当我更改任何数字时,我的代码不会更新数字的上一个或下一个数字。 此外,子不会返回错误。 任何build议,为什么会是这种情况?

Sub Worksheet_Change(ByVal Target As Range) If Target.Cells.Count > 1 Or IsEmpty(Target) Then Exit Sub If IsNumeric(Target) Then If Application.WorksheetFunction.Sum(Cells(1, Target.Column), Cells(5, Target.Column)) <> 100 Then If Target.Row > 1 Then Cells(Target.Row - 1, Target.Column).Value = Cells(Target.Row - 1, Target.Column).Value + 100 - Application.Sum(Cells(1, Target.Column), Cells(5, Target.Column)) Else Cells(Target.Row + 1, Target.Column).Value = Cells(Target.Row + 1, Target.Column).Value + 100 - Application.Sum(Cells(1, Target.Column), Cells(5, Target.Column)) End If End If End If End If End Sub 

谢谢你的帮助!

你有几个问题:

  1. 正如共产国际在评论中指出的,你有一个End If这不匹配一个If 。 (你可能打算把它作为单行If ,但是单行If不需要End If 。)

  2. 在代码运行时,不要禁用事件发生,当您从代码启动另一个更改时,可能会导致奇怪的事情发生。 (主要只是在设定值时才是问题。)

  3. 您的Sum函数只添加第1行和第5行中的数字。

您的代码的重构版本将如下所示:

 Sub Worksheet_Change(ByVal Target As Range) If Target.Cells.Count > 1 Or IsEmpty(Target) Then Exit Sub Application.EnableEvents = False If IsNumeric(Target) Then If Application.Sum(Range(Cells(1, Target.Column), Cells(5, Target.Column))) <> 100 Then If Target.Row > 1 Then Cells(Target.Row - 1, Target.Column).Value = Cells(Target.Row - 1, Target.Column).Value + 100 - Application.Sum(Range(Cells(1, Target.Column), Cells(5, Target.Column))) Else Cells(Target.Row + 1, Target.Column).Value = Cells(Target.Row + 1, Target.Column).Value + 100 - Application.Sum(Range(Cells(1, Target.Column), Cells(5, Target.Column))) End If End If End If Application.EnableEvents = True End Sub