Click here to Skip to main content
15,888,984 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
how to delete Selected row , but if selected row is First row or last row then dont delete in Excel VBA (Macro)


VB
Sub deleterow()

ActiveSheet.Unprotect

Dim MyRange As Object
    ' Store the selected range in a variable.
    Set MyRange = Selection
    
    
    
    ' Select the entire column.
    Selection.EntireRow.Select
    
      
    ' Insert Columns in all selected sheets.
    Selection.delete
    
    ' Reselect the previously selected cells.
    
    ActiveSheet.Protect DrawingObjects:=False, Contents:=True, Scenarios:= _
        False, AllowFormattingCells:=True, AllowFormattingColumns:=True, _
        AllowFormattingRows:=True, AllowInsertingColumns:=True, AllowInsertingRows _
        :=True, AllowInsertingHyperlinks:=True, AllowDeletingColumns:=True, _
        AllowDeletingRows:=True, AllowSorting:=True, AllowFiltering:=True, _
        AllowUsingPivotTables:=True
    

End Sub
Posted
Updated 20-Aug-15 2:58am
v2
Comments
Maciej Los 20-Aug-15 9:22am    
Are you sure that first and last row can't be deleted?

1 solution

I'll improve your code to 3 lines:

VB
ActiveSheet.Unprotect
ActiveCell.EntireRow.Delete Shift:=xlShiftUp
ActiveSheet.Protect ...


For further information, please see: Range.Delete Method (Excel)[^]

Note: your code is potentially dangerous, because it works no matter of context! What it means? It deletes row from currently active sheet. If you would like to delete row from desired sheet, use something like this:
VB
Dim wsh As Worksheet
'...
Set wsh = ThisWorkbook.Worksheets("Sheet1")
wsh.ActiveCell.EntireRow.Delete Shift:=xlShiftUp
'...
 
Share this answer
 
v2
Comments
Wendelius 20-Aug-15 14:04pm    
Nice answer, 5
Maciej Los 20-Aug-15 17:02pm    
Thank you, Mika.
HimenDev 21-Aug-15 0:40am    
actually i want to put condition for first row and last row...
that if my selected row is first row or last row then dont delete otherwise it should be deleted...
i dont have any issue regarding sheet ..i have only one sheet available so...
HimenDev 21-Aug-15 0:41am    
i want one more thing...like if my selected row contains particular word then dont delete otherwise delete selected row....
Maciej Los 23-Aug-15 15:36pm    
I don't get you ;(

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900