Determine whether user is adding or deleting rows

前端 未结 7 2224

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

    There are two a bit another approaches both based on the following template.

    1. Define a module or class module variable of Range type.
    2. “Pin” a special range by assigning it to the variable using absolute address and save its address or size (it depends on approach).
    3. To determine a subtype of user action manipulate with the variable in a sheet change event handler.

    In the first approach the whole range of interest is assigned to the variable and range's size is saved. Then in a sheet change event handler the following cases must be processed:

    • an exception occurs when accessing Address property => the pinned range is no longer exist;
    • the address of changed cell is below then pinned range => an insertion was => update the variable
    • a new size of the pinned range is different from saved (smaller => something was deleted, bigger => something was inserted).

    In the second approach a “marker” range is assigned to the variable (see example below) and the range address is saved in order to determine movements or shifts in any direction. Then in a sheet change event handler the following cases must be processed::

    • an exception occurs when accessing Address property => the pinned “marker” range is no longer exist;
    • the address of changed cell is below then "marker" range => an insertion was => update the variable
    • there is a difference in any direction, i.e. abs(new_row - saved_row) > 0 or abs(new_col-saved_col) > 0 => the pinned range was moved or shifted.

    Pros:

    • User-defined name is not used
    • UsedRange property is not used
    • A pinned range is updated accordingly to user actions instead of assumption that a user action will not occur below 1000-th row.

    Cons:

    • The variable must be assigned in a workbook open event handler in order to use it in a sheet change event handler.
    • The variable and a WithEvents-variable of object must be assigned to Nothing in a workbook close event handler in order to unsubscribe form the event.
    • It is impossible to determine sort operations due to they change value of range instead of exchange rows.

    The following example shows that both approaches could work. Define in a module:

    Private m_st As Range
    Sub set_m_st()
      Set m_st = [$A$10:$F$10]
    End Sub
    Sub get_m_st()
      MsgBox m_st.Address
    End Sub
    

    Then run set_m_st (simply place a cursor in the sub and call Run action) to pin range $A$10:$F$10. Insert or delete a row or cell above it (don't confuse with changing cell(s) value). Run get_m_st to see a changed address of the pinned range. Delete the pinned range to get "Object required" exception in get_m_st.

提交回复
热议问题