Determine whether user is adding or deleting rows

前端 未结 7 2188

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

    Capture row additions and deletions in the worksheet_change event.

    I create a named range called "CurRowCnt"; formula: =ROWS(Table1). Access in VBA code with:

    CurRowCnt = Evaluate(Application.Names("CurRowCnt").RefersTo)
    

    This named range will always hold the number of rows 'after' a row(s) insertion or deletion. I find it gives a more stable CurRowCnt than using a global or module level variable, better for programming, testing and debugging.

    I save the CurRowCnt to a custom document property, again for stability purposes.

    ThisWorkbook.CustomDocumentProperties("RowCnt").Value = Evaluate(Application.Names("CurRowCnt").RefersTo)
    

    My Worksheet_Change Event structure is as follows:

    Dim CurRowCnt as Double
    CurRowCnt = Evaluate(Application.Names("CurRowCnt").RefersTo)
    Select Case CurRowCnt
    
        '' ########## ROW(S) ADDED
         Case Is > ThisWorkbook.CustomDocumentProperties("RowCnt").Value
             Dim r As Range
             Dim NewRow as Range
    
             ThisWorkbook.CustomDocumentProperties("RowCnt").Value = _
             Evaluate(Application.Names("CurRowCnt").RefersTo)
    
             For Each r In Selection.Rows.EntireRow
                 Set NewRow = Intersect(Application.Range("Table1"), r)
                 'Process new row(s) here
             next r
    
        '' ########## ROW(S) DELETED
         Case Is < ThisWorkbook.CustomDocumentProperties("RowCnt").Value
    
             ThisWorkbook.CustomDocumentProperties("RowCnt").Value = _
             Evaluate(Application.Names("CurRowCnt").RefersTo)
    
             'Process here
    
        '' ########## CELL CHANGE
        'Case Is = RowCnt
    
            'Process here
    
        '' ########## PROCESSING ERROR
        Case Else 'Should happen only on error with CurRowCnt or RowCnt
            'Error msg here
    
    End Select
    
    0 讨论(0)
提交回复
热议问题