Home » excel » vba – Excel Autofilter all but variable value

vba – Excel Autofilter all but variable value

Posted by: admin March 9, 2020 Leave a comment

Questions:

So I need to filter all the values in a row except one.
I got it to work, using this part of code, which obviously will filter on everything, but “Belgium”, but I need there to be variable.

Dim myValue As Variant
myValue = InputBox("Which country to exclude? ")

Range("AB1").Select
ActiveSheet.Range("$B$1:$BY$319696").AutoFilter Field:=27, Criteria1:="<>Belgium"

For the version of filter where I filter on a particular country the variable works just fine:

Dim myValue As Variant
myValue = InputBox("Which country to filter on: ")

Range("AB1").Select
ActiveSheet.Range("$B$1:$BY$319696").AutoFilter Field:=27, Criteria1:= _
    myValue
ActiveWindow.SmallScroll Down:=-30

So why would this not work:

ActiveSheet.Range("$B$1:$BY$319696").AutoFilter Field:=27, Criteria1:= <>myValue

Also I do not know why it is structured like this, it was generated from Record Macro, especially the _
Criteria1:= _
myValue

How to&Answers:

The “<>” isn’t an operator (which is how you tried to use it in the “not working” example), but rather needs to be part of the string you are passing to the AutoFilter (which is how you did it in the working first example.)

ActiveSheet.Range("$B$1:$BY$319696").AutoFilter Field:=27, Criteria1:= "<>" & myValue should work.