Option Explicit
Const strText As String = "FindMe"
Sub ColSearch_DelRows()
Dim rng1 As Range
Dim rng2 As Range
Dim rng3 As Range
Dim cel1 As Range
Dim cel2 As Range
Dim strFirstAddress As String
Dim lAppCalc As Long
Dim bParseString As Boolean
'Get working range from user
On Error Resume Next
Set rng1 = Application.InputBox("Please select range to search for " & strText, "User range selection", Selection.Address(0, 0), , , , , 8)
On Error GoTo 0
If rng1 Is Nothing Then Exit Sub
'No further processing of matches
bParseString = False
With Application
lAppCalc = .Calculation
.ScreenUpdating = False
.Calculation = xlCalculationManual
End With
'a) match string to entire cell, case insensitive
Set cel1 = rng1.Find(strText, , xlValues, xlWhole, xlByRows, , False)
'b) match string to entire cell, case sensitive
'Set cel1 = rng1.Find(strText, , xlValues, xlWhole, xlByRows, , True)
'c)match string to part of cell, case insensititive
' Set cel1 = rng1.Find(strText, , xlValues, xlPart, xlByRows, , False)
'd)match string to part of cell, case sensititive
' Set cel1 = rng1.Find(strText, , xlValues, xlPart, xlByRows, , True)
'A range variable - rng2 - is used to store the range of cells that contain the string being searched for
If Not cel1 Is Nothing Then
Set rng2 = cel1
strFirstAddress = cel1.Address
Do
Set cel1 = rng1.FindNext(cel1)
Set rng2 = Union(rng2.EntireRow, cel1)
Loop While strFirstAddress <> cel1.Address
End If
'Further processing of found range if required
'This sample looks to delete rows that contain the text in StrText AND where column A contains "Duplicate"
If Not bParseString Then
If Not rng2 Is Nothing Then rng2.EntireRow.Delete
Else
For Each cel2 In rng2.Rows
If Cells(cel2.Row, "A").Value = "Duplicate" Then
If Not rng3 Is Nothing Then
Set rng3 = Union(rng3, cel2.EntireRow)
Else
Set rng3 = cel2.EntireRow
End If
End If
Next
If Not rng3 Is Nothing Then rng3.EntireRow.Delete
End If
With Application
.ScreenUpdating = True
.Calculation = lAppCalc
End With
End Sub
Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.
Comments (1)
Commented:
I was thinking about an article like yours while answering this question.
https://www.experts-exchange.com/questions/26466861/How-to-delete-rows-in-excel-with-VBA.html
One of the points I was going to make related to deleting items in lists and arrays as well as rows in a worksheet. One of the dangers that programmers face when doing deletions is deleting items in front-to-back order, which changes the list as it shrinks. Depending on the code, rows might be skipped or incorrect rows might be deleted.
===========
Thank you for showing the partial match parameter. Which parameter configuration would you use for wildcard matches?