Worksheet_Change事件在另一个宏运行后停止工作

时间:2016-05-23 09:32:06

标签: excel vba events

当我运行另一个宏时,这个停止工作。让它回到正轨的唯一方法是在即时窗口中运行以下命令。

Application.EnableEvents = True

这是我的代码:

Private Sub Worksheet_Change(ByVal Target As Range)
    Application.EnableEvents = False
    Application.ScreenUpdating = False

    Dim lastrow As String, x, row, irow, column, total As Double
    lastrow = Range("B8").End(xlDown).Value + 7

    Range("Pump_design[Total Pipe losses from plantroom]").ClearContents
    For Each row In Columns("FB")
        For irow = 8 To lastrow
            total = 0
            For column = 6 To 153
                x = Cells(irow, column).Value
                If Not IsEmpty(x) Then
                    total = total + Application.WorksheetFunction.vlookup(x, Sheets("Pump Design").Range("Pump_design"), 155, False)
                End If
            Next column
            Cells(irow, "FB") = total
            If Cells(irow, "FB") = 0 Then Cells(irow, "FB").ClearContents
        Next irow
        row = irow + 1
    Next row

    Application.ScreenUpdating = True
    Application.EnableEvents = True

End Sub

以下是使上述宏停止工作的代码:

Sub delete_row()
    Application.ScreenUpdating = False
    Application.EnableEvents = False

    Dim LastrowPD As Long, PDi As String, PDj As Integer
    LastrowPD = Sheets("Pump Design").ListObjects("pump_design").Range.Rows.Count
    PDi = LastrowPD - 1
    If IsNumeric(PDi) Then PDj = Val(PDi)
    If PDj = 1 Then Exit Sub
    Sheets("Pump Design").Activate
    Sheets("Pump Design").ListObjects("pump_design").Range.Select
    Selection.ListObject.ListRows(PDj).Delete
    Range("A1").Select
    Application.EnableEvents = True
    Application.ScreenUpdating = True
End Sub 

2 个答案:

答案 0 :(得分:0)

不说这是一个解决方案,我想指出一些错误:

Dim lastrow As String, x, row, irow, column, total As Double

在上面一行中,lastrowStringtotalDouble。所有其他vaiables都是Variant。我相信这不是你的意思。

lastrow一个String,我想知道它在执行时的价值是什么:

lastrow = Range("B8").End(xlDown).Value + 7

在循环逻辑中:

For Each row In Columns("FB")
    For irow = 8 To lastrow
        ....
    Next irow
    row = irow + 1
Next row

我想知道irow循环对lastrowString的影响。在此循环结束时,irowVariant,因此可能是String,将大于lastrow(现在假设它是Integer }})。然后执行

    row = irow + 1
Next row

但由于rowFor Each语句管理,否则这将完全混淆Each,或者该语句无效。

我建议您首先清除所有这些错误,然后再检查代码是否正常运行。

答案 1 :(得分:0)

 If PDj = 1 Then Exit Sub

这就是问题所在。因为你要退出潜艇,你不会重新开启事件。相反,你可以反转逻辑:

If PDj <> 1 Then 
    Sheets("Pump Design").Activate
    Sheets("Pump Design").ListObjects("pump_design").Range.Select
    Selection.ListObject.ListRows(PDj).Delete
    Range("A1").Select
end if
    Application.EnableEvents = True
    Application.ScreenUpdating = True