I want a macro to filter a sheet for all instances of our corporate email address regardless of which column they are in (50+ columns). I have tried Autofilter
and AdvancedFilter
without success. AdvancedFilter
seems most likely, but I cannot find examples of the syntax for CriteriaRange
.
I have read <>text
can be used for wildcards, but have no idea how to use it.
The worksheet has the column headers in rows 10-11 (not my sheet, so I cannot change it).
My most recent attempt gives an Expected expression error:
Sub AdvancedFilter()
If Sheets(2).FilterMode = True Then
Sheets(2).ShowAllData
End If
Sheets(2).Range("A13:CO100").AdvancedFilter _
Action:=xlFilterInPlace, _
CriteriaRange:=(*mydomain.com)
End Sub
Please, try the next way. It should be very fast, hiding the rows not containing the searched domain:
Sub filterByDomain()
Dim sh As Worksheet, lastR As Long, lastCol As Long, rng As Range
Dim rngHidd As Range, findC As Range, iRow As Range
Const dom As String = "mydomain.com"
Set sh = ActiveSheet 'use here the necessary sheet
lastR = sh.Range("A" & sh.rows.count).End(xlUp).Row 'last row
lastCol = sh.cells(13, sh.Columns.count).End(xlToLeft).column 'last column on the headers row
Set rng = sh.Range("A13", sh.cells(lastR, lastCol)) 'the range to be processed
rng.EntireRow.Hidden = False 'unhide the previously hidden rows
For Each iRow In rng.Resize(rng.rows.count - 1).Offset(1).rows 'iterate between rng rows, except the header:
Set findC = iRow.Find(dom, iRow.cells(1), xlValues, xlPart)
If findC Is Nothing Then 'if not finding the searched domain, place first row cell in a `Union` range
addToRange rngHidd, iRow.cells(1)
End If
Next
'hide the rows not containing the searched domain, at once:
If Not rngHidd Is Nothing Then rngHidd.EntireRow.Hidden = True
MsgBox "Ready..."
End Sub
Sub addToRange(rngU As Range, rng As Range) 'helping sub to build the Union range
If rngU Is Nothing Then
Set rngU = rng
Else
Set rngU = Union(rngU, rng)
End If
End Sub