0

Good day.

The following code does what I want, i.e. correctly filters my data.

ActiveSheet.Range("$A$1:$AV$791").AutoFilter Field:=5, Criteria1:=Array( _
        "Delta", "Ladner", "Tsawwassen"), Operator:=xlFilterValues

But, I want to use variables to change and filter different cities. The following code gives me the accompanying string.

cityStr = """Delta""" & ", " & """Ladner""" & ", " & """Tsawwassen"""
returns the string:  "Delta", "Ladner", "Tsawwassen"

But when I put the variable into the filter statement it doesn't do anything. It doesn't matter if I use quotes around cityStr - neither works.

ActiveSheet.Range("$A$1:$AV$791").AutoFilter Field:=5, Criteria1:=Array( _
    cityStr), Operator:=xlFilterValues

Any suggestions on how to use a variable in an array?

Thanks Les

5
  • Did you debug and check what is the final value after the value is substituted in the variable? Commented Jul 20, 2015 at 17:24
  • Yes, the variable shows as "Delta", "Ladner", "Tsawwassen". Autofilter doesn't seem to recognize this string if its in a variable. The result is that nothing is filtered and creates a filtered list with nothing in it. Commented Jul 20, 2015 at 17:40
  • The autofilter works fine if I use a single variable, such as deltaStr = "Delta" and I remove the Array. So the autofilter statement ends with Criteria1:=deltaStr. This works fine, its the variable in an array that I'm having trouble with. Commented Jul 20, 2015 at 17:48
  • Refer this article Commented Jul 20, 2015 at 17:48
  • @Nimesh: I placed the string "Delta", "Ladner", "Tsawwassen" into a cell. I changed my code to: dim cityStr as Object - set cityStr = ActiveSheet.cells(1,1) - Criteria1:=cityStr.Value. Unfortunately, I have the same result, which was nothing. Commented Jul 20, 2015 at 18:45

1 Answer 1

3

It wants an array, so give it an array

Sub test()
Dim ws As Worksheet
Set ws = ActiveSheet
Dim rng As Range
Set rng = ws.Range("A1:A10")
Dim CityStr() As Variant
CityStr() = Array("Delta", "Ladner", "octopus")
rng.AutoFilter field:=1, Criteria1:=CityStr(), Operator:=xlFilterValues
End Sub

Declare a variant array, fill it with your strings, and use it as criteria1. I think you have to use a variant per kb.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. That seems to have done the trick. I will try it with different variables.

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.