Determine whether user is adding or deleting rows

前端 未结 7 2229

I have a VBA macro that validates user entered data (I didn\'t use data validation/conditional formatting on purpose).

I am using Worksheet_Change event

7条回答
  •  清歌不尽
    2020-11-29 10:52

    Try this code:

    Private Sub Worksheet_Change(ByVal Target As Range)
        Dim lNewRowCount As Long
    
        ActiveSheet.UsedRange
        lNewRowCount = ActiveSheet.UsedRange.Rows.Count
    
        If lOldRowCount = lNewRowCount Then
        ElseIf lOldRowCount > lNewRowCount Then
            MsgBox ("Row Deleted")
            lOldRowCount = lNewRowCount
        ElseIf lOldRowCount < lNewRowCount Then
            MsgBox ("Row Inserted")
            lOldRowCount = lNewRowCount
        End If
    
    End Sub
    

    Also add this in the ThisWorkBook module:

    Private Sub Workbook_Open()
        ActiveSheet.UsedRange
        lOldRowCount = ActiveSheet.UsedRange.Rows.Count
    End Sub
    

    And then this in its own module:

    Public lOldRowCount As Long
    

    The code assumes you have data in row 1. Note the very first time you run it you make get a false result, this is because the code needs to set the lRowCount to the correct variable. Once done it should be okay from then on in.

    If you don't want to use the Public variable and worksheet open event then you could use a named range on your worksheet somewhere and store the row count (lRowCount) there.

提交回复
热议问题