For Loop in Worksheet 更改故障

For Loop in Worksheet change malfunction

拜托,我有一个问题,每次 sheet 上发生更改都会影响所有行,而不是相关的行 (i)。使困惑。 for 循环不适用于 worksheet_change 吗?请帮助。谢谢

Private Sub Worksheet_Change(ByVal Target As Range)

Dim LR As Long

'create a variable for last row of column C, LR
LR = Cells(Rows.Count, "C").End(xlUp).Row


For i = 2 To LR
      If Cells(i, 6) = "Yes" And Cells(i, 7).Value = "Full" Then 
       Target.Value = Cells(i, 3).Value
       Cells(i, 9).ClearContents
       Cells(i, 10).Value = Cells(i, 8).Value + Cells(i, 9).Value
     End If
    
    If Not Intersect(Target, Range("G" & i & ":G" & LR)) Is Nothing And Range("F" & i) = "Yes" 
    And Target.Value = "Full" Then
      Application.EnableEvents = False
      Cells(i, 8).Value = Cells(i, 3).Value
      Cells(i, 9).ClearContents
      Cells(i, 10).Value = Cells(i, 8).Value + Cells(i, 9).Value
      Application.EnableEvents = True
    End If
    
    If Not Intersect(Target, Range("G" & i & ":G" & LR)) Is Nothing And Range("F" & i) = "Yes" And 
    Target.Value = "Portion" Then
      Application.EnableEvents = False
      Cells(i, 8).Value = Cells(i, 3).Value
      Cells(i, 10).Value = Cells(i, 8).Value + Cells(i, 9).Value
      Application.EnableEvents = True
    End If
    
Next i
End Sub

 

您似乎需要为 A-E 列启动此事件。因此,您可以使用以下命令启动您的宏:

IF Target.Column <= 5 THEN
...
END IF 'at the end of your macro

像这样,当你启动像Cells(i, 8).Value = ...Cells(i, 10).Value = ...这样的代码时,...这个宏将被调用,但它会立即停止。

显然您正在检查最多 10 列,该列在您要在宏中更改的单元格范围内。让我们换一种方法:

在你的宏的最开始,放这行:

Application.EnableEvents = False

在你的宏的最后,把这行:

Application.EnableEvents = True

(并删除其他事件)。

这将确保您不会在 运行 调用宏时调用它。