0

I am trying to create a search box that Autofilters as you type. I have used a variety of tutorials but I am struggling to get it working correctly.

The code I am using is:

Private Sub SearchField_Change()
If Len(SearchField.Value) = 0 Then
    Sheet1.AutoFilterMode = False
Else
    If Sheet1.AutoFilterMode = True Then
        Sheet1.AutoFilterMode = False
    End If
Sheet1.Range ("A:A" & Rows.Count) .AutoFilter _ Field:= 1, Criteria1:="*" & SearchField.Value & "*"
End If
End Sub

I am receiving a Syntax error when I try to use this, what I find confusing is that I am copying what is on tutorials (changing the sheet names/textbox names as appropriate) yet no success.

2 Answers 2

1

You need to specify the filter range correctly. The first cell in the range which is being filtered should be your header. So if the headers are in Row 2, try it like this...

Sheet1.Range("A2:A" & Rows.Count).AutoFilter Field:=1, Criteria1:="*" & SearchField.Value & "*"
Sign up to request clarification or add additional context in comments.

Comments

0

The flaw is in that:

Range("A:A" & Rows.Count)

Which would try referencing some "A:A1000000" range, which is obviuolsly an error

Then you want to use:

Range("A1:A" & Rows.Count)

Or, which is the same:

Range("A:A")

But I wouldn't reference the whole column and limit the range to the actually “used” one

So you may try this little refactoring of your code:

Private Sub SearchField_Change()
    With Sheet1
        .AutoFilterMode = False
        If Len(SearchField.Value) = 0 Then Exit Sub
        .Range("A1", .Cells(.Rows.Count,1).End(xlUp)).AutoFilter Field:= 1, Criteria1:="*" & SearchField.Value & "*"
    End With
End Sub

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.