delete rows based on set of numbers (vba macro)

excelNewbie22

Well-known Member
Joined
Aug 4, 2021
Messages
528
Office Version
  1. 365
Platform
  1. Windows
hi!
so i tried with watching videos in youtube, searching and testing for hours for several days, with no success
but i found a vba macro partly to my needs,
which is to delete ANY row without ANY or ALL the numbers i'll set (like 5 6 7 or more)
didn't manage to redefine the range (all rows in current sheet)
can you please help me out?

VBA Code:
Sub DeleteRows()
' Defines variables
Dim Cell As Range, cRange As Range, LastRow As Long, x As Long


' Defines LastRow as the last row of data based on column A
LastRow = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row


' Sets check range as A1 to the last row of A
Set cRange = Range("A1:A" & LastRow)

' For each cell in the check range, working from the bottom upwards
For x = cRange.Cells.Count To 1 Step -1
    With cRange.Cells(x)
        ' If the cell does not contain one of the listed values then...
        If .Value <> "5" And .Value <> "6" And .Value <> "7" Then
            ' Delete that row
            .EntireRow.Delete
        End If
    End With
' Check next cell, working upwards
Next x


End Sub

example:
567.xlsx
ABCD
61127
71128
81132
91133
101134
111135
121136
131137
141138
151142
161143
171144
181145
191146
201147
211148
221152
231153
241154
251155
261156
271158
281162
291163
301164
311165
321166
331167
341168
351172
567
 

Excel Facts

Which lookup functions find a value equal or greater than the lookup value?
MATCH uses -1 to find larger value (lookup table must be sorted ZA). XLOOKUP uses 1 to find values greater and does not need to be sorted.
Deleting rows in a loop can be slow. Also keeping track of what numbers to delete. You may want to use Autofilter with Array to remove unwanted rows? Something like this?

VBA Code:
Option Explicit

Sub Sample()
    Dim col As New Collection
    Dim itm As Variant
    Dim i As Long, j As Long, k As Long
    Dim lRow As Long
    Dim MyArray() As String
    Dim ws As Worksheet
    Dim IsInArray As Boolean
 
    '~~> Change this to the relevant Sheet
    Set ws = Sheet1
 
    '~~> Change the dimension as required.
    '~~> Any number other than these will be deleted
    Dim ExcludeArray(1 To 3) As Variant
    ExcludeArray(1) = 5
    ExcludeArray(2) = 6
    ExcludeArray(3) = 7
 
    With ws
        .AutoFilterMode = False
    
        lRow = .Range("A" & .Rows.Count).End(xlUp).Row
    
        '~~> Get a unique count of items in the column. Assuming first cell has Header
        For i = 2 To lRow
            On Error Resume Next
            col.Add .Cells(i, 1).Value2, CStr(.Cells(i, 1).Value2)
            On Error GoTo 0
        Next i
    
        k = col.Count
    
        '~~> Find how many numbers are there which needs to be deleted
        For Each itm In col
            For j = LBound(ExcludeArray) To UBound(ExcludeArray)
                If itm = ExcludeArray(j) Then
                    k = k - 1
                    Exit For
                End If
            Next j
        Next itm
            
        '~~> Store the numbers to be deleted in an array
        ReDim MyArray(1 To k)
        k = 1
    
        For Each itm In col
            On Error Resume Next
            IsInArray = Application.Match(itm, ExcludeArray, 0)
            On Error GoTo 0
    
            If IsInArray = False Then
                MyArray(k) = itm
                k = k + 1
            Else
                IsInArray = False
            End If
        Next itm
    
        '~~> Use Autofilter to delete the rows in 1 go
        With .Range("A1:A" & lRow)
            .AutoFilter Field:=1, Criteria1:=MyArray, Operator:=xlFilterValues
            .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow.Delete
        End With
    
       .AutoFilterMode = False
    End With
End Sub

1641669073675.png
 
Upvote 0
thanks for helping
it give me an error
 

Attachments

  • 1641670138989.png
    1641670138989.png
    2.6 KB · Views: 10
Upvote 0
only the sheet name to "Sheet1"
everything else is good

p.s
first cell has no header

Sheet1.xlsx
ABCD
11122
21123
31124
Sheet1


also the file length is about 4k lines
 
Upvote 0
the highlighted was :
VBA Code:
Set ws = Sheet1
search google and tried changing to:
VBA Code:
 Set ws = ThisWorkbook.Worksheets(1)
it worked
but it deleted too many lines in the 4k lines file
for the example above it deleted all lines
were it should delete only lines numbers: 8-9-10-14-15-16-17-21
 
Upvote 0
the highlighted was :
VBA Code:
Set ws = Sheet1
search google and tried changing to:
VBA Code:
 Set ws = ThisWorkbook.Worksheets(1)
it worked
but it deleted too many lines in the 4k lines file
for the example above it deleted all lines
were it should delete only lines numbers: 8-9-10-14-15-16-17-21

Sheet1 in my code was the code name of the worksheet. You can see the code name from the Visual basic Editor Project Explorer. It is advisable to either use the code name or use something like ThisWorkbook.Worksheets("SomeName"), where "SomeName" is the name of worksheet. If there is only 1 worksheet in the workbook then it is ok to use ThisWorkbook.Worksheets(1) but if you have more than 1, it is not advisable to use this because you many never know which sheet might be at the 1st index.

Can you share the exact code that you are using?
 
Upvote 0
thanks for explaining

the code you gave me:
VBA Code:
Option Explicit

Sub Sample()
    Dim col As New Collection
    Dim itm As Variant
    Dim i As Long, j As Long, k As Long
    Dim lRow As Long
    Dim MyArray() As String
    Dim ws As Worksheet
    Dim IsInArray As Boolean
 
    '~~> Change this to the relevant Sheet
    Set ws = ThisWorkbook.Worksheets(1)
 
    '~~> Change the dimension as required.
    '~~> Any number other than these will be deleted
    Dim ExcludeArray(1 To 3) As Variant
    ExcludeArray(1) = 5
    ExcludeArray(2) = 6
    ExcludeArray(3) = 7
 
    With ws
        .AutoFilterMode = False
    
        lRow = .Range("A" & .Rows.Count).End(xlUp).Row
    
        '~~> Get a unique count of items in the column. Assuming first cell has Header
        For i = 2 To lRow
            On Error Resume Next
            col.Add .Cells(i, 1).Value2, CStr(.Cells(i, 1).Value2)
            On Error GoTo 0
        Next i
    
        k = col.Count
    
        '~~> Find how many numbers are there which needs to be deleted
        For Each itm In col
            For j = LBound(ExcludeArray) To UBound(ExcludeArray)
                If itm = ExcludeArray(j) Then
                    k = k - 1
                    Exit For
                End If
            Next j
        Next itm
            
        '~~> Store the numbers to be deleted in an array
        ReDim MyArray(1 To k)
        k = 1
    
        For Each itm In col
            On Error Resume Next
            IsInArray = Application.Match(itm, ExcludeArray, 0)
            On Error GoTo 0
    
            If IsInArray = False Then
                MyArray(k) = itm
                k = k + 1
            Else
                IsInArray = False
            End If
        Next itm
    
        '~~> Use Autofilter to delete the rows in 1 go
        With .Range("A1:A" & lRow)
            .AutoFilter Field:=1, Criteria1:=MyArray, Operator:=xlFilterValues
            .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow.Delete
        End With
    
       .AutoFilterMode = False
    End With
End Sub
 
Upvote 0
1. Since there are no headers,

VBA Code:
For i = 2 To lRow

becomes

VBA Code:
For i = 1 To lRow

2. I see you have not changed the numbers to be exlcuded. It is still 5,6 and 7. So any other number other than these will be deleted. Lets say you do not want to delete 1,4,8,10 then you need to change

VBA Code:
    Dim ExcludeArray(1 To 3) As Variant
    ExcludeArray(1) = 5
    ExcludeArray(2) = 6
    ExcludeArray(3) = 7

to

VBA Code:
    Dim ExcludeArray(1 To 4) As Variant
    ExcludeArray(1) = 1
    ExcludeArray(2) = 4
    ExcludeArray(3) = 8
    ExcludeArray(4) = 10

So now amend the code to accordingly and try again?
 
Upvote 0

Forum statistics

Threads
1,223,243
Messages
6,170,971
Members
452,371
Latest member
Frana

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