简体   繁体   中英

Autofilter by inputting array by selecting a range of crieteria vba excel

edit # 1 I am trying to autofilter a sheet based on the criteria as an array, the array values are selected by using the dialog box to select the range.Also, this dialog box's intent is to select multiple unsorted values that need to be sorted.Here is the code:

Sub Hyperlink_opener()
Dim Selrng As Range
Dim srch_cr As Variant
Set Selrng = Application.InputBox("Select a range", "Obtain Range Object", Type:=8)

srch_cr = Array(Selrng)
Sheets("DocLog").Select
ActiveSheet.Range("$A:$F").AutoFilter Field:=1, Criteria1:=srch_cr, Operator:=xlFilterValues
'ActiveWindow.SmallScroll Down:=-15

End Sub

This is currently not searching for the cell that i selected and is giving me an error Autofilter method of range class failed.

This will do it as long as your selected range contains text, or numbers stored as text:

Sub Hyperlink_opener()
Dim Selrng As Range
Dim srch_cr As Variant

Set Selrng = Application.InputBox("Select a range", "Obtain Range Object", Type:=8)
srch_cr = Application.WorksheetFunction.Transpose(Selrng)
Sheets("DocLog").Range("$A:$F").AutoFilter Field:=1, Criteria1:=srch_cr, Operator:=xlFilterValues
End Sub

Note that you need to transpose the range to turn it to a single-dimension range. Also, no need to Select the sheet, just refer to it.

If you have numbers that need to be filtered, you can either store them as text in your filter range or convert them to text in the code by parsing the array.

Based on your Operator:=xlOr , I think you'd like to filter on multiple criteria.

According to Microsoft's docs (for Excel 2010), you can have 2 criteria, and the Operator:= tells it what to do with the two of them. In your case, the code would be:

ActiveSheet.Range("$a:$F").AutoFilter Field:=1, _
             Criteria1:=Srch_Cr(1), Criteria2:=Srch_Cr(2), Operator:=xlOr

You cannot simply pass an array to the Criteria1 parameter and assume the .AutoFilter function will figure out what to do with it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM