PDA

View Full Version : Please configure my code with automatic filter



Master_Viper
07-23-2016, 11:30 AM
Hello Expert,

Could someone configure my code. When the range of the code was until column D to G the search button is working, but if I would like to extend the to column D to P I got an error.
Please the error in red font below together with the codes.


Sub UserSearch_Click()
Dim myButton As OptionButton
Dim SearchString As String
Dim ButtonName As String
Dim sht As Worksheet
Dim myField As Long
Dim DataRange As Range
Dim mySearch As Variant
'Load Sheet into A Variable
Set sht = ActiveSheet
'Unfilter Data (if necessary)
On Error Resume Next
sht.ShowAllData
On Error GoTo 0

'Filtered Data Range (include column heading cells)
Set DataRange = sht.Range("D10:M300") 'Cell Range
'Set DataRange = sht.ListObjects("ER100_Activation_Configuration").Range 'Table
'Retrieve User's Search Input
'mySearch = sht.Shapes("UserSearch").TextFrame.Characters.Text 'Control Form
'mySearch = sht.OLEObjects("UserSearch").Object.Text 'ActiveX Control
mySearch = sht.Range("E4").Value 'Cell Input

'Determine if user is searching for number or text
If IsNumeric(mySearch) = True Then
SearchString = "=" & mySearch
Else
SearchString = "=*" & mySearch & "*"
End If

'Loop Through Option Buttons
For Each myButton In sht.OptionButtons
If myButton.Value = 1 Then
ButtonName = myButton.Text
Exit For
End If
Next myButton

'Determine Filter Field
On Error GoTo HeadingNotFound
myField = Application.WorksheetFunction.Match(ButtonName, DataRange.Rows(1), 0)
On Error GoTo 0

'Filter Data
DataRange.AutoFilter _
Field:=myField, _
Criteria1:=SearchString, _
Operator:=xlAnd

'Clear Search Field
'sht.Shapes("UserSearch").TextFrame.Characters.Text = "" 'Control Form
'sht.OLEObjects("UserSearch").Object.Text = "" 'ActiveX Control
sht.Range("E7").Value = "" 'Cell Input

Exit Sub
'ERROR HANDLERS
HeadingNotFound:
MsgBox "The column heading [" & ButtonName & "] was not found in cells " & DataRange.Rows(1).Address & ". " & _
vbNewLine & "Please check for possible typos.", vbCritical, "Header Name Not Found!"

End Sub


Thanks for helping me again.

p45cal
07-23-2016, 01:48 PM
Well, I've tried rigging up a sheet and the code seems to be fine. Of course changing to:
Set DataRange = sht.Range("D10:P300")
Next stage is for you to supply a workbook with this happening.