Super User Asked by Dhivya Sethu on November 12, 2021
I’m looking to filter a column based on a code the user puts into an input box.
I used the following code:
Sub Filter()
'
' Filter Macro
Dim strName As String
strName = InputBox(“What DMA would you like to search for?”)
Selection.AutoFilter
ActiveSheet.Range("$A$1:$AS$355969").AutoFilter Field:=3, Criteria1:="=*" & strName & “ * ”, Operator:=xlAnd
End Sub
But it shows compile error:
Syntax error in Excel Macro
Can someone help me, please?
A very useful tutorial.
More advanced filtering can be achieved by adding a textbox control to the worksheet.
I created a template to filter on the worksheet based on the searched value (letters, numbers or other characters) in textbox , using the VBA Find and AutoFilter methods. The filtered cells are listed on the worksheet, the number of filtered cells is informed to the user by msgbox.
I hope it benefits to users.
I created the template using the VBA find and findnext methods in the do - while loop :
...
Sheets("Data").Cells.EntireRow.Hidden = False
If Not aCell Is Nothing Then
Set bCell = aCell
Range("AN2").Value = aCell.Address(False, False)
Do
son = 0
Set aCell = Range("F4:F" & Range("F" & Rows.Count).End(xlUp).Row).FindNext(After:=aCell)
If Not aCell Is Nothing Then
If aCell.Address = bCell.Address Then Exit Do
son = son + 1
Range("AN" & Rows.Count).End(xlUp).Offset(son, 0).Value = aCell.Address(False, False)
Else
Exit Do
End If
Loop
Label1.Visible = False
Else
Label1.Visible = False
Range("G2").Activate
MsgBox SearchString & " Not Found", vbCritical, ""
Exit Sub
End If
...
Answered by kadrleyn on November 12, 2021
You may try this simple code to filter:
Sub InputFilter()
Dim strInput As String
strInput = InputBox("Enter your value to filter on")
Selection.AutoFilter
ActiveSheet.Range("$A$60:$A$65").AutoFilter Field:=1, Criteria1:=strInput
End Sub
N.B. Remember Field
value in the code is adjustable if the Criteria matches the Column 2 to filter then it should be Field:=2
Note, adjust cell references as needed.
Answered by Rajesh Sinha on November 12, 2021
I am going to assume you want wildcard matching so you do not need the additional white space in the second wildcard. In addition you need correct "" and switching off ScreenUpdating is a good idea. You can also use a With statememt for your range. Better would be to use an explicit sheet name rather than Activesheet in case the current Activesheet is not the one you were expecting.
Option Explicit
Public Sub Filter()
Application.ScreenUpdating = False
Dim strName As String
strName = InputBox("What DMA would you like to search for?")
With ActiveSheet.Range("$A$1:$AS$355969")
.AutoFilter
.AutoFilter Field:=3, Criteria1:="*" & strName & "*"
End With
Application.ScreenUpdating = True
End Sub
Answered by user778123 on November 12, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP