VBA - Stop deletion passed a certain row range

Eios000

New Member
Joined
May 25, 2021
Messages
7
Office Version
  1. 2016
Platform
  1. Windows
Afternoon all,

I had this code that when I initially placed it in, stopped the entire row from being deleted if it was A4 and it worked fine.

For whatever reason (gremlins) it is no longer working and know matter what, the message box always appears. Does anyone know why? I've tried modifying it to be A3, however when tested it deletes A4 and then seems to work...

VBA Code:
Sub RemoveLastRow()
If Range("A" & Rows.Count).End(xlUp) = ActiveSheet.Range("A4") Then 'stops deletion
    MsgBox "Cannot delete any further."
    Exit Sub
End If
ActiveSheet.Cells(Rows.Count, "A").End(xlUp).EntireRow.Delete 'selects the last row of the sheet and deletes
End Sub
 

Excel Facts

Bring active cell back into view
Start at A1 and select to A9999 while writing a formula, you can't see A1 anymore. Press Ctrl+Backspace to bring active cell into view.
It's because "Value" is the default property of a range object, so you are comparing values instead of cell locations. You could change this

VBA Code:
If Range("A" & Rows.Count).End(xlUp) = ActiveSheet.Range("A4") Then 'stops deletion

to this

VBA Code:
If Range("A" & Rows.Count).End(xlUp).Address = "$A$4" Then 'stops deletion

or this

VBA Code:
If Range("A" & Rows.Count).End(xlUp).Row <= 4 Then  'stops deletion
 
Upvote 0
Awesome, I used that bottom solution and it worked perfectly! Thanks!
 
Upvote 0
I you mean to delete any row(s) after row 4, then you should create a loop.
Alternatively, you could find the last row, and if the row number is greater than 4, delete all the rows from row 5 till the last row.
 
Upvote 0

Forum statistics

Threads
1,214,978
Messages
6,122,549
Members
449,089
Latest member
davidcom

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top