Determine whether user is adding or deleting rows

前端 未结 7 2231

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:35

    After searching for a bit decided to solve it myself. In your Worksheet module (e.g. Sheet1 under Microsoft Excel Objects in VBA Editor) insert the following:

    Private usedRowsCount As Long 'use private to limit access to var outside of sheet
    
    'Because select occurs before change we can record the current usable row count
    Private Sub Worksheet_SelectionChange(ByVal Target As Range)
      usedRowsCount = Target.Worksheet.UsedRange.rows.count 'record current row count for row event detection
    End Sub
    
    'once row count recorded at selection we can compare the used row count after change occurs
    'with the Target.Address we can also detect which row has been added or removed if you need to do further mods on that row
    Private Sub Worksheet_Change(ByVal Target As Range)
      If usedRowsCount < Target.Worksheet.UsedRange.rows.count Then
        Debug.Print "Row Added: ", Target.Address
      ElseIf usedRowsCount > Target.Worksheet.UsedRange.rows.count Then
        Debug.Print "Row deleted: ", Target.Address
      End If
    End Sub
    

提交回复
热议问题