【问题标题】:Mutually link three cells --> infinite loop?相互链接三个单元-> 无限循环?
【发布时间】:2018-03-24 09:06:13
【问题描述】:

我以两种方式链接多个单元格,这意味着如果我更改一个,另一个将更新,反之亦然。 此代码适用于两个单元格

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address = "$B$4" Then
        'Application.EnableEvents = False
        Sht_input.Range("E4").Value = Sht_input.Range("B4").Value
        'Application.EnableEvents = True
    End If

    If Target.Address = "$E$4" Then
        'Application.EnableEvents = False
         Sht_input.Range("b4").Value = Sht_input.Range("e4").Value
        'Application.EnableEvents = True
    End If
 End Sub

现在,当我尝试链接三个单元格时,代码进入不定式循环

Private Sub Worksheet_Change(ByVal Target As Range)

    If Target.Address = "$B$4" Then
        'Application.EnableEvents = False
        Sht_input.Range("E4").Value = Sht_input.Range("B4").Value
        Sht_input.Range("h4").Value = Sht_input.Range("B4").Value
        'Application.EnableEvents = True
    End If

    If Target.Address = "$E$4" Then
        'Application.EnableEvents = False
        Sht_input.Range("b4").Value = Sht_input.Range("e4").Value
        Sht_input.Range("h4").Value = Sht_input.Range("e4").Value
        'Application.EnableEvents = True
    End If

    If Target.Address = "$H$4" Then
        'Application.EnableEvents = False
        Sht_input.Range("b4").Value = Sht_input.Range("H4").Value
        Sht_input.Range("e4").Value = Sht_input.Range("H4").Value
        'Application.EnableEvents = True
    End If
End Sub

我试图调试,但我不明白为什么即使不再选择目标单元格,它也会回到“if”。谁能帮帮我?

【问题讨论】:

    标签: excel vba infinite-loop


    【解决方案1】:

    您需要禁用这些事件。否则它总是会陷入无限循环,单元格值正在被更改。是否是相同的值无关紧要。

    Application.EnableEvents = False
    
    If Target.Address = "$B$4" Then
        Sht_input.Range("E4").Value = Sht_input.Range("B4").Value
        Sht_input.Range("h4").Value = Sht_input.Range("B4").Value
    End If
    
    If Target.Address = "$E$4" Then
    
        Sht_input.Range("b4").Value = Sht_input.Range("e4").Value
        Sht_input.Range("h4").Value = Sht_input.Range("e4").Value
    
    End If
    
    If Target.Address = "$H$4" Then
        Sht_input.Range("b4").Value = Sht_input.Range("H4").Value
        Sht_input.Range("e4").Value = Sht_input.Range("H4").Value
    End If
    Application.EnableEvents = True
    

    注意在代码开头和结尾所做的更改。

    【讨论】:

    • Shrivallabha:请问运行代码 sn-p 按钮和其他按钮是如何添加的?
    • QHarr:我从代码 sn-p 中删除了错误的标签。它是 VBA。
    • 我还以为我发现了一些新奇迹 :-)
    • @QHarr 如果您在回答时单击代码按钮,则会打开一个新表单,您可以在其中粘贴代码。然后除了包装代码之外,还会自动添加按钮。我是这个网站的新手,所以你可能会期望我不会出现这样的错误;)
    猜你喜欢
    • 2018-04-04
    • 1970-01-01
    • 2012-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-01
    • 2012-05-01
    相关资源
    最近更新 更多