如何调试简单的Worksheet_Change

时间:2019-06-21 09:50:20

标签: excel vba

我正在尝试更改单元格的值以显示为文本,否则将使用公式将其合并到另一个单元格下;该脚本似乎可以正常工作,但调试消息不断弹出,如果尝试多次,则会导致文件崩溃。

我使用的代码是如此简单,以至于我无法弄清它是怎么回事...?

Private Sub Worksheet_Change(ByVal Target As Range)  
    Dim Note As Range
    Set Note = Sheets("Interface").Range("D2")

    Sheets("Intake Note").Range("G5").Value = Note
End Sub

我希望单元格G5具有使用公式合并在一起的单元格D2中显示的所有内容的实际文本。

2 个答案:

答案 0 :(得分:1)

问题在于,如果此Worksheet_Change在工作表Intake Note中,则此工作表中的任何更改都会再次触发该事件。因此,这是一个无休止的循环,因为事件更改了一个单元格……触发了事件,该事件更改了一个单元格……依此类推。

因此,您需要在此事件中更改单元格之前禁用Application.EnableEvents property

Private Sub Worksheet_Change(ByVal Target As Range)  
    Dim Note As Range
    Set Note = Worksheets("Interface").Range("D2")

    Application.EnableEvents = False
    Worksheets("Intake Note").Range("G5").Value = Note 'this line would trigger another Worksheet_Change event 
    Application.EnableEvents = True 
End Sub

但是我仍然相信您应该在名为Interface的工作表的Worksheet.Calculate event中进行所有这些操作。

答案 1 :(得分:0)

我认为应该是:

Sheets("Intake Note").Range("G5").Value = Note.Value 
                                                     # instead of:
Sheets("Intake Note").Range("G5").Value = Note