macro not deleting proper rows.count

michaelsmith559

Well-known Member
Joined
Oct 6, 2013
Messages
881
Office Version
  1. 2013
  2. 2007
I am using the below macro to delete rows that are less than 4 or greater than 9. The macro runs correctly except for deleting the correct row count. The macro is leaving selected ranges with row counts greater than 9. Here is the macro:

Code:
nlr = Cells(Rows.Count, 12).End(xlUp).Row
For i = nlr To 2 Step -1
    myval = Cells(i, "L").Value
    lr = Cells(Rows.Count, 1).End(xlUp).Row
    lastcolumn = _
        Cells.Find(What:="*", After:=Range("A1"), SearchOrder:=xlByColumns, _
        SearchDirection:=xlPrevious).Offset(0, -5).Column
add1 = Columns(1).Find(What:=myval, LookIn:=xlValues, LookAt:=xlWhole).Row
xrow = add1
Do
If Cells(xrow + 1, 1).Value <> myval Then
    add2 = xrow + 1
    Exit Do
Else
    xrow = xrow + 1
End If
Loop Until xrow = lastrow
add2 = xrow
Range(Cells(add1, 1), Cells(add2, lastcolumn)).Select
mycount = Selection.Rows.Count
    
If mycount < 4 Or mycount > 9 Then
    Selection.Delete Shift:=xlUp
End If
Next i
 

Excel Facts

What is the fastest way to copy a formula?
If A2:A50000 contain data. Enter a formula in B2. Select B2. Double-click the Fill Handle and Excel will shoot the formula down to B50000.
Less than 4 or 9 what?
Is that the value in a certain column?

It is a bit confusing as to what all your code before the delete steps is supposed to be doing.
It might be helpful to post a sample of your data to go along with your explanation, and tell us based on that what exactly should happen.
 
Upvote 0
I found the problem, a range was not being set correctly. The variable mycount counts the rows in the selected range and if the rows count is less than 4 or greater than 9 it deletes the rows.
 
Upvote 0

Forum statistics

Threads
1,214,649
Messages
6,120,733
Members
448,987
Latest member
marion_davis

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