当您在A,C和D列中复制粘贴值时,我无法使下面的代码生效。例如,如果我在row2中,并且我在单元格A2,C2和D2中插入数据,则代码执行此操作它的工作。但是如果我在第3,4,5行中复制粘贴数据,则代码不再检查条件。如果有人能帮助我解决这个问题我真的很感激。谢谢!
Sub LogicalPart(i As Long)
If (Cells(i, "C") + Cells(i, "D")) <> Cells(i, "A") Then
MsgBox "C" & i & " + D" & i & " must equal cell A" & i & " which is: " & Range("A" & i).Value
MsgBox ("Please insert again the data in cell C" & i & " or D " & i & "!")
Cells(i, "C").Interior.Color = RGB(255, 0, 0)
Cells(i, "D").Interior.Color = RGB(255, 0, 0)
Else
Range(Cells(i, "C"), Cells(i, "D")).Interior.Color = RGB(1000, 1000, 1000)
End If
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Application.Intersect(Range("C1:d10"), Target) Is Nothing Then
LogicalPart Target.row
End If
End Sub
答案 0 :(得分:3)
您需要迭代目标范围内的行:
Target.Row
只返回第一行而不是全部:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim rng As Range
Dim rngrow As Range
Set rng = Intersect(Range("C1:d10"), Target)
If Not rng Is Nothing Then
For Each rngrow In rng.Rows
LogicalPart rngrow.Row
Next rngrow
End If
End Sub