VBA结束如果没有阻止如果我的困境

VBA结束如果没有阻止如果我的困境,vba,excel,excel-formula,Vba,Excel,Excel Formula,所以我得到了一个错误:End If没有block If,我是VBA新手,并且尝试将其他线程的答案应用到我自己的线程中,但运气不佳。你能帮帮我吗。 提前谢谢 Private Sub Worksheet_Change(ByVal Target As Range) Dim KeyCells As Range ' The variable KeyCells contains the cells that will ' cause an alert when they are c

所以我得到了一个错误:End If没有block If,我是VBA新手,并且尝试将其他线程的答案应用到我自己的线程中,但运气不佳。你能帮帮我吗。 提前谢谢

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim KeyCells As Range

    ' The variable KeyCells contains the cells that will
    ' cause an alert when they are changed.
    Set KeyCells = Range("B2:B6")

    If Not Application.Intersect(KeyCells, Range(Target.Address)) _
           Is Nothing Then

        ' Display a message when one of the designated cells has been
        ' changed.
        ' Place your code here.
        MsgBox "Cell " & Target.Address & " has changed."
        For Each KeyCells In Range(Target.Address)
        If KeyCells.Value <> "" Then KeyCells.Value = KeyCells.Value & "-CN"
        Next
    End If
End Sub
Private子工作表\u更改(ByVal目标作为范围)
暗淡的关键单元格作为范围
'变量KeyCells包含将
'因为当它们被更改时会发出警报。
设置关键单元=范围(“B2:B6”)
如果不是应用程序.Intersect(关键单元格,范围(目标地址))_
那就什么都不是了
'当其中一个指定单元格已被删除时,显示一条消息
”“变了。
'将代码放在这里。
MsgBox“单元格”和目标地址已更改
对于范围内的每个关键单元(Target.Address)
如果KeyCells.Value为“”,则KeyCells.Value=KeyCells.Value&“-CN”
下一个
如果结束
端接头

为了确保只触发一次,您需要关闭代码内部的
事件,因为代码本身会更改单元格,从而再次触发您正在处理的确切事件

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim KeyCells As Range

    ' The variable KeyCells contains the cells that will
    ' cause an alert when they are changed.
    Set KeyCells = Range("B2:B6")

    If Not Application.Intersect(KeyCells, Target) _
           Is Nothing Then 'since Target is range it will suffice here


        MsgBox "Cell " & Target.Address & " has changed."

        Application.EnableEvents = False 'turn off events to avoid endless loop

        For Each KeyCells In Range(Target.Address)
            If KeyCells.Value <> "" Then  KeyCells.Value = KeyCells.Value & "-CN"
        Next

        Application.EnableEvents = True 'turn back on so events continue to fire

    End If

End Sub
Private子工作表\u更改(ByVal目标作为范围)
暗淡的关键单元格作为范围
'变量KeyCells包含将
'因为当它们被更改时会发出警报。
设置关键单元=范围(“B2:B6”)
如果不是Application.Intersect(关键单元格,目标)_
因为目标是射程,所以这里就足够了
MsgBox“单元格”和目标地址已更改
Application.EnableEvents=False“关闭事件以避免无休止的循环
对于范围内的每个关键单元(Target.Address)
如果KeyCells.Value为“”,则KeyCells.Value=KeyCells.Value&“-CN”
下一个
Application.EnableEvents=True'重新打开,以便事件继续激发
如果结束
端接头

您发布的代码在语法上很好,编译时没有错误。无论它是多么好的代码,因为它将导致无限循环-您需要禁用事件!同意@Rory,但您的代码确实会产生无止境的循环。我在B2中进行了更改,每次单击
确定
,当它在已更改的单元格中输入
-CN
时,会触发工作表更改事件,再次触发此代码。我如何将For循环更改为仅运行一次?在更改事件代码中,每当您更改代码中单元格的值时,更改事件再次被触发。为了避免在更改单元格内容的行之前出现这种情况,请使用Application.EnableEvents=False禁用事件,然后在单元格中进行所需的更改后,不要忘记使用Application.EnableEvents=True.FWIW再次启用事件。任何不匹配的块编译错误的答案(例如,“If without End If”),压痕是否正确/正确。如果您不确定如何做到这一点,那么还有(我管理的是一个开源项目)。我否决了这个问题,因为代码没有重现它所问的问题。