Filter numeric field - vba

I have the following code:
ActiveSheet.Range("$A$1:$P$201").AutoFilter Field:=5, Criteria1:="=10"*
When I click on the filter and type in the search bar 10* I get all results that start with 10. When using the macro, that doesn't work. The goal is for the macro to filter using the first two numbers provided by me.
Can you assist?

The core of the problem seems to have been trying to apply a text filter to a numeric field.
Instead of:
ActiveSheet.Range("$A$1:$P$201").AutoFilter Field:=5 ActiveSheet.Range("$A$1:$P$201").AutoFilter Field:=5, Criteria1:="=10"*
just:
ActiveSheet.Range("$A$1:$P$201").AutoFilter Field:=5, _
Criteria1:=">=10000", Operator:=xlAnd, Criteria2:="<=10999"
seems to have worked.

The following will work only if the values are text:
Sub Macro2()
ActiveSheet.Range("$A$1:$P$201").AutoFilter Field:=5, Criteria1:="=10*", _
Operator:=xlAnd
End Sub
If the values are not text, then use a "helper" column.
EDIT#1:
For postal codes in column E, this will filter out (hide) rows not containing "10*" codes:
Sub GoingPostal()
Dim r As Range
For Each r In Range("E2:E201")
st = Left(r.Text, 2)
If st <> "10" Then
r.EntireRow.Hidden = True
End If
Next r
End Sub

Related

Make search field in VBA Excel dynamicly focus results

I have a large Excel sheet and to that I have added a dynamic search field textbox and that works fine.
Private Sub TextBox1_Change()
ActiveSheet.Range("E6:E150").AutoFilter Field:=4, Criteria1:="*" & [G1000] & "*", Operator:=xlFilterValues
End Sub
The problem is that if I filter out say row number 500 the result is not visible so I have to manually move the cursor up.
I tried this (and a lot of other stuff) without success.
Private Sub TextBox1_Change()
With ActiveSheet.Range("E6:E150").AutoFilter Field:=4, Criteria1:="*" & [G1000] & "*", Operator:=xlFilterValues
.Select
End With
End Sub
It yield this
"run-time error '424': Object required"
Any help is appreciated.
Perhaps the first visible cell above the currently selected but hidden activecell.
Private Sub TextBox1_Change()
with ActiveSheet
.Range("E6:E150").AutoFilter Field:=1, Criteria1:="*" & [G1000] & "*"
if activecell.EntireRow.hidden then
dim i as long
for i=activecell.row to 6 step-1
if not .cells(i, activecell.column).EntireRow.hidden then
.cells(i, activecell.column).select
exit for
end if
next i
end if
end with
End Sub
I've changed the AutoFilter field to 1 as there aren't 4 fields in Range("E6:E150"); there is only 1. Also removed the unnecessary Operator:=xlFilterValues as that is only required when using an array as Criteria1.
Sorry for being unprecise.
Using select is no good idea I can see from implementing Jeepeds answer.
I found what I'm after:
Private Sub TextBox1_Change()
With ActiveSheet
.Range("E6:E150").AutoFilter Field:=4, Criteria1:="" & [G1000] & ""
ActiveWindow.ScrollRow = 1
End With
End Sub
Just that simple.

Excel VBA AutoFilter on user selection run-time error 1004

I have an Excel 2010 workbook containing 2 sheets ("Contents" and "Folders").
The purpose of this workbook is to track different pieces of work by supplier or reference number, with a front-end (the Contents page) that is simple to use, consisting only of buttons and a search box (Which isn't actually a separate box, but simply the contents of cell J8 of the Contents sheet (hereafter referred to as J8) as typed by the user.
The buttons will filter by supplier type (and work perfectly fine) but it's the user selection that I'm having trouble with.
My code for this macro is:
Sub Find_Click()
Dim userSelect As String
userSelect = "*" & Range("J8") & "*"
Sheets("Folders").Select
ActiveSheet.Range("$B$1:$B$5000").AutoFilter Field:=2, Criteria:=userSelect, Operator:=x1And
End Sub
When the 'Find' button is pressed, this should read J8, then select the Folders sheet and filter the result to show every entry in column B that contains the text in J8.
This was working fine. However, now when I try to use this macro I get a 1004 run-time error with the 'Application-defined or object-defined error' message.
Can anyone please help?
EDIT:
The Contains buttons that have macros assigned that follow this format:
Sub Button1_Click()
Sheets("Folders").Select
ActiveSheet.Range("$A$1:$A$5000").AutoFilter Field:=1, Criteria1:= _
"Criteria"
Set r = Range(Range("A3"), Range("A3").End(xlDown))
j = WorksheetFunction.CountA(r.Cells.SpecialCells(xlCellTypeVisible))
'MsgBox j
If j = 0 Then
MsgBox "There is currently no work relating to Criteria"
ActiveSheet.AutoFilterMode = False
ActiveSheet.Range("A3").Select
Sheets("Contents").Select
End If
End Sub
There is also a resest button that clears a filter and returns to the Contents sheet:
Sub Reset_Click()
ActiveSheet.ShowAllData
Sheets("Contents").Select
End Sub
Generally, you'll need to activate a cell inside the range in which you are going to use the AutoFilter.
Further more, when you are trying to use AutoFilter with wildcards (* or ?) or math test, you'll need to add an = at the start of your criteria string, so
userSelect = "=*" & Range("J8") & "*"
Then, it is not Criteria, but Criteria1 and Criteria2 if you use a second one! So you don't need an Operator in this case.
And finally with ActiveSheet.Range("$B$1:$B$5000").AutoFilter Field:=2, you are asking the code to filter on the second column of a range where there is only one column!
So if you want to filter on col B, just change Field:=2 to Field:=1
Here is the working code :
Sub Find_Click()
Dim userSelect As String
Dim wS as Worksheet
userSelect = "=*" & Range("J8") & "*"
Set wS = Sheets("Folders")
wS.Activate
wS.Range("B1").Activate
If Not wS.AutoFilterMode Then wS.AutoFilterMode = True
wS.Range("$B$1:$B$5000").AutoFilter Field:=1, Criteria1:=userSelect
End Sub
And you also had a typo in xlAnd, it was x1And ;)
For anyone who is interested, the problem ended up being in the line:
ActiveSheet.Range("$B$1:$B$5000").AutoFilter Field:=2, Criteria1:=userSelect
As the code was filtering only column B, the Field value needed to be set to '1' instead of my original '2'
Thanks to #R3uK for his invaluable help!

Referencing multiple cells VBA Autofilter

I am using the following code to apply an autofilter to a range and filter on one of the columns by looking for the same value that is contained in several reference cells:
Sub filter()
Range("B6:N9000").AutoFilter Field:=2, Criteria1:=Array(Range("C2").Value, Range("D2").Value, Range("E2").Value )
End Sub
The problem however is the filter only applies the LAST cell referenced in the code, ie for above it ONLY looks up "E2", not "C2" & "D2" & "E2"
Any suggestions? Thanks
To put an answer under this: You want to add the argument Operator:=xlFilterValues to your call, so it will look like this:
Range("B6:N9000").AutoFilter Field:=2, Criteria1:=Array(Range("C2").Value, _
Range("D2").Value, Range("E2").Value), Operator:=xlFilterValues
or
[B6:N9000].AutoFilter Field:=2, _
Criteria1:=Array([C2].Value, [D2].Value, [E2].Value), Operator:=xlFilterValues

Filter to exclude formula and blank

Filter field has many numbers, formula (result is "-") and blank.
How to write a VBA code to filter all numbers and exclude "-" and blank.
"-" is not text or string it's the result of a formula.
On Error Resume Next
ActiveSheet.ShowAllData
Range("G8").AutoFilter Filed:=7, Criteria2:="="
Range("N8").AutoFilter Field:=14, Criteria1:="<>-", _
Operator:=xlAnd, Criteria2:="<>"
Try this:
Edit1: For your example, it should be:
Range("N8").AutoFilter Field:=1, Criteria1:="<>-" _
, Criteria2:="<>", Operator:=xlAnd
This will filter out blanks and cells with - as a result of formula.
Take note that you're only working one Cell N8 which only have 1 field of data.
Edit2: Another way to make it work is to explicitly define the range you're working on.
Dim r As Range
Set r = Sheets("Sheet1").Range("A1:N100") 'change to suit
r.AutoFilter Field:=14, Criteria1:="<>-" _
, Criteria2:="<>", Operator:=xlAnd
Is this what you're trying? HTH.

Set Auto Filtering multiple wildcards

Right now I am doing coding to set a filter for a data chart. Basically, I don't know how to post the data sheet up here so just try to type them ):
(starting from the left is column A)
Name * BDevice * Quantity * Sale* Owner
Basically I need to filter out for 2 column:
-The BDevice with any word contain "M1454" or "M1467" or "M1879" (It means that M1454A or M1467TR would still fit in)
-The Owner with PROD or RISK
Here is the code I wrote:
Sub AutoFilter()
ActiveWorkbook.ActiveSheet..Range(B:B).Select
Selection.Autofilter Field:=1 Criteria1:=Array( _
"*M1454*", "*M1467*", "*M1879*"), Operator:=xlFilterValues
Selection.AutoFilter Field:=4 Criteria1:="=PROD" _
, Operator:=xlOr, Criteria2:="=RISK"
End Sub
When I run the code, the machine returns error 1004 and the part which seems to be wrong is the Filter part 2 ( I am not sure about the use of Field, so I can not say it for sure)
Edit; Santosh: When I try your code, the machine gets error 9 subscript out of range. The error came from the with statement. (since the data table has A to AS column so I just change to A:AS)
While there is a maximum of two direct wildcards per field in the AutoFilter method, pattern matching can be used to create an array that replaces the wildcards with the Operator:=xlFilterValues option. A Select Case statement helps the wildcard matching.
The second field is a simple Criteria1 and Criteria2 direct match with a Operator:=xlOr joining the two criteria.
Sub multiWildcardFilter()
Dim a As Long, aARRs As Variant, dVALs As Object
Set dVALs = CreateObject("Scripting.Dictionary")
dVALs.CompareMode = vbTextCompare
With Worksheets("Sheet1")
If .AutoFilterMode Then .AutoFilterMode = False
With .Cells(1, 1).CurrentRegion
'build a dictionary so the keys can be used as the array filter
aARRs = .Columns(2).Cells.Value2
For a = LBound(aARRs, 1) + 1 To UBound(aARRs, 1)
Select Case True
Case aARRs(a, 1) Like "MK1454*"
dVALs.Add Key:=aARRs(a, 1), Item:=aARRs(a, 1)
Case aARRs(a, 1) Like "MK1467*"
dVALs.Add Key:=aARRs(a, 1), Item:=aARRs(a, 1)
Case aARRs(a, 1) Like "MK1879*"
dVALs.Add Key:=aARRs(a, 1), Item:=aARRs(a, 1)
Case Else
'no match. do nothing
End Select
Next a
'filter on column B if dictionary keys exist
If CBool(dVALs.Count) Then _
.AutoFilter Field:=2, Criteria1:=dVALs.keys, _
Operator:=xlFilterValues, VisibleDropDown:=False
'filter on column E
.AutoFilter Field:=5, Criteria1:="PROD", Operator:=xlOr, _
Criteria2:="RISK", VisibleDropDown:=False
'data is filtered on MK1454*, MK1467* or MK1879* (column B)
'column E is either PROD or RISK
'Perform work on filtered data here
End With
If .AutoFilterMode Then .AutoFilterMode = False
End With
dVALs.RemoveAll: Set dVALs = Nothing
End Sub
If exclusions¹ are to be added to the filtering, their logic should be placed at the top of the Select.. End Select statement in order that they are not added through a false positive to other matching criteria.
                                Before applying AutoFilter Method
                                After applying AutoFilter w/ multiple wildcards
¹ See Can Advanced Filter criteria be in the VBA rather than a range? and Can AutoFilter take both inclusive and non-inclusive wildcards from Dictionary keys? for more on adding exclusions to the dictionary's filter set.
For using partial strings to exclude rows and include blanks you should use
'From Jeeped's code
Dim dVals As Scripting.Dictionary
Set dVals = CreateObject("Scripting.Dictionary")
dVals.CompareMode = vbTextCompare
Dim col3() As Variant
Dim col3init As Integer
'Swallow row3 into an array; start from 1 so it corresponds to row
For col3init = 1 to Sheets("Sheet1").UsedRange.Rows.count
col3(col3init) = Sheets("Sheet1").Range(Cells(col3init,3),Cells(col3init,3)).Value
Next col3init
Dim excludeArray() As Variant
'Partial strings in below array will be checked against rows
excludeArray = Array("MK1", "MK2", "MK3")
Dim col3check As Integer
Dim excludecheck as Integer
Dim violations As Integer
For col3check = 1 to UBound(col3)
For excludecheck = 0 to UBound(excludeArray)
If Instr(1,col3(col3check),excludeArray(excludecheck)) <> 0 Then
violations = violations + 1
'Sometimes the partial string you're filtering out for may appear more than once.
End If
Next col3check
If violations = 0 and Not dVals.Exists(col3(col3check)) Then
dVals.Add Key:=col3(col3check), Item:=col3(col3check) 'adds keys for items where the partial strings in excludeArray do NOT appear
ElseIf col3(col3check) = "" Then
dVals.Item(Chr(61)) = Chr(61) 'blanks
End If
violations = 0
Next col3check
The dVals.Item(Chr(61)) = Chr(61) idea came from Jeeped's other answer here
Multiple Filter Criteria for blanks and numbers using wildcard on same field just doesn't work
Try below code :
max 2 wildcard expression for Criteria1 works. Refer this link
Sub AutoFilter()
With ThisWorkbook.Sheets("sheet1").Range("A:E")
.AutoFilter Field:=2, Criteria1:=Array("*M1454*", "*M1467*"), Operator:=xlFilterValues
.AutoFilter Field:=5, Criteria1:="=PROD", Operator:=xlOr, Criteria2:="=RISK"
End With
End Sub