Run a macro only when deleing a row

B

BG Lad

Can anyone get me started on where I might put some code that runs when a row
or any cell is deleted in the worksheet?
 
G

Gary''s Student

Put this Event macro in the worksheet code area:

Dim rowcount As Long
Private Sub Worksheet_Change(ByVal Target As Range)
If IsEmpty(rowcount) Then
Else
If ActiveSheet.UsedRange.Rows.Count = rowcount - 1 Then
MsgBox ("a row was deleted")
End If
End If
rowcount = ActiveSheet.UsedRange.Rows.Count
End Sub

It relies on detecting that the number of rows in UsedRange has been reduced
by one. Because it is worksheet code, it is very easy to install and use:

1. right-click the tab name near the bottom of the window
2. select View Code - this brings up a VBE window
3. paste the stuff in and close the VBE window

If you save the workbook, the macro will be saved with it.

To remove the macro:

1. bring up the VBE windows as above
2. clear the code out
3. close the VBE window

To learn more about macros in general, see:

http://www.mvps.org/dmcritchie/excel/getstarted.htm

To learn more about Event Macros (worksheet code), see:

http://www.mvps.org/dmcritchie/excel/event.htm
 
R

Rick Rothstein

You declared the 'rowcount' variable as a Long, but then you do an IsEmpty
test inside the subroutine. IsEmpty will always return False for a variable
declared as anything other than a Variant.
 
R

Rick Rothstein

Yes. That makes it "global" to the code module it is on and it will retain
its value after the subroutine that puts a value in it ends. If you declared
it inside the subroutine, then any values assigned to it would disappear
when the subroutine ended. Usually a variable is declared outside of a
subroutine or function in the (General)(Declarations) section of the code
window so that more than one subroutine and/or function can reference its
value. That is not how Gary''s Student is using it, though; rather, he is
using the fact that this kind of declaration preserves values while the code
windows remains active. Another way to have handled this would have been to
declare the variable as Static inside the subroutine itself... doing that
would insure no other procedures would be able to change it, but Static
variable retain their values from subroutine call to subroutine call.

Look up "Understanding Scope and Visibility" in the VB help files for more
information on this. Also look up the "Static Statement" in the VB help
files too.
 
B

BG Lad

Right, but I was referring to the position in code of the Dim statement. If
it is to be located before the "Private Sub ... " statement then it is moved
into the "(General)" section "(Declarations)", is this correct?
 
R

Rick Rothstein

See my direct response to where you asked that question the first time... my
comment in this subthread was directed to Gary''s Student who posted the
original code.
 
Top