删除单元格值Worksheet_Change事件时崩溃

时间:2019-01-14 21:10:14

标签: excel vba

只要值在给定范围(F5至LastRow)中,我都希望在工作表上连续运行一个宏(例如test1)。在这方面,Worksheet_Activate和Worksheet_Change事件提供了帮助。但是,只要删除范围内的值,Excel就会崩溃。例如:

F5 = 100,F6 = 120,F7 = 140

假设F5的值更改为120。然后宏和事件运行正常。但是,当所有值都删除后(因此F5更新F7为空),Excel崩溃。

我试图单独运行代码中的每一行,但是我不确定是什么原因导致崩溃(也许是宏中写的循环)?

我是VBA的初学者,非常感谢您的帮助:-)

Sub TEST()

 Dim LastRow As Long
 Dim i As Long

 LastRow = Sheets("blad1").Range("F5").End(xlDown).Row

 For i = 5 To LastRow

 Range("Z" & i).Formula = "=ABS(F" & i & " -(J" & i & " *(100/21)))< 5" 
 'Checks if the value in column F matches the amount in column J for each 
 'cellin that column with a significance of 5. The return is shown as 
 'True or False.
  Next i

 For i = 5 To LastRow

 If Range("Z" & i) = True Then Range("F" & i).Interior.Color = RGB(255, 
 255, 255) Else: Range("F" & i).Interior.Color = RGB(255, 0, 0) 
 'If the 
 'value in column Z is True, then the cell colour in column F is white. 
 'If False, then red.
 Next i

 End Sub

 'These are the lines on the relevant worksheet:

 Private Sub Worksheet_Activate()

 Call test

 End Sub

 Private Sub Worksheet_Change(ByVal Target As Range)

 Dim LastRow As Long
 LastRow = Sheets("Test").Range("F5").End(xlDown).Row

 If Not Intersect(Target, Me.Range("F5:F" & LastRow)) Is Nothing Then
    Application.EnableEvents = False
    Call test
    Application.EnableEvents = True
  End If

 End Sub

1 个答案:

答案 0 :(得分:1)

LastRow = Sheets("blad1").Range("F5").End(xlDown).Row
当列F为空时,

返回的值等于可能的最后一行绝对值(1048576)。然后,宏的其余部分将遍历整个工作表,为每一行执行代码。您可以想象当您尝试将1048572公式插入电子表格时会发生什么。更好的选择是使用

LastRow = Sheets("blad1").Range("F" & Rows.Count).End(xlUp).Row

从上至下获取最后使用的行。然后,您可以将Worksheet_Change逻辑更改为

If LastRow > 1 Then
    'Code Here
End if

编辑:

同样值得注意的是,当LastRow = Sheets("blad1").Range("F5").End(xlDown).Row时,此代码

If Not Intersect(Target, Me.Range("F5:F" & LastRow)) Is Nothing Then
    Application.EnableEvents = False
    Call test
    Application.EnableEvents = True
End If
当您在F列中的值大于第4行的任何行号上编辑

时,始终会评估True,因为Intersect()基本上说“如果范围1和范围2重叠返回true”。因此,Range("F7")Range("F5:F1048576")之内,无论它是否具有值。