删除行后无法重新运行宏



我试图运行代码来验证列"K"。如果列"K"中的任何单元格为Null,则应该弹出错误消息,单元格应该变为红色。我尝试了下面的代码,它正在工作。以下是我的问题。我运行宏。宏检测Null单元格并弹出错误消息。我删除了行与空单元格。再次运行宏。再次弹出错误消息。K列的最后一个单元格变为红色,尽管该行没有任何数据。

这是我使用的代码

Sub Errormsg ()
count2 = Range("B:B").SpecialCells(xlLastCell).Row
For n = 2 To count2
If Range("K" & n).Value = vbNullString Then
Range("K" & n).Interior.ColorIndex = 3
MsgBox "Error ! Null value "
Exit Sub
End If                  
Next n
End Sub 

使用另一列(如ID或永远不会为空的东西),并在IF语句中使用

Sub Errormsg ()
count2 = Range("B:B").SpecialCells(xlLastCell).Row
For n = 2 To count2
    If Range("K" & n).Value = vbNullString AND Range("A" & n).Value <> "" Then
        Range("K" & n).Interior.ColorIndex = 3
        MsgBox "Error ! Null value "
        Exit Sub
    End If                  
Next n
End Sub 

实际上,您的代码也在最后一行工作。从循环中删除最后一行。会好的。

Sub Errormsg ()
     count2 = Range("B:B").SpecialCells(xlLastCell).Row
     For n = 2 To count2 - 1 'Just modify it
         If Range("C" & n).Value = vbNullString Then
             Range("C" & n).Interior.ColorIndex = 3
             MsgBox ("Error ! Null value ")
             Exit Sub
         End If
     Next n
End Sub

最新更新