简体   繁体   中英

Getting the values from a column based on a string from another column and returning a unique list from result

I have a table that has two columns that I'm interested in. What I want to do is lookup a string in the the first column but save the strings from the second column in a range. Also I would like the values to be unique.

I was thinking of looping through the entire first column, but given that I have in excess of 20000 rows I was wondering if there are better methods that will automatically find the values and save them as a range.

Here's and example of how my table looks:

在此处输入图片说明

So what I want is save as a range all the strings in column D when column A has value AAA, for example. I know that I can do this easily with advanced filter but I want to do it in VBA.

Thanks

Use something like this:

Sub FilterRange(WS As Worksheet, FieldIndex As Long, CriteriaStr As String)
    WS.AutoFilterMode = False
    Set Rng = WS.UsedRange
    Rng.AutoFilter FieldIndex, CriteriaStr, Operator:=xlFilterValues, VisibleDropDown:=False
End Sub

Call it like this:

Sub Test()

    Dim WS As Worksheet: Set WS = ThisWorkbook.Sheets("Sheet3") 'Modify as necessary.
    Dim ColOfCondition As Long
    ColOfCondition = Application.Match("HeaderA", WS.Rows(1), 0)
    FilterRange WS, ColOfCondition, "AAA"

End Sub

Gives a result like this:

在此处输入图片说明

Let us know if this helps.

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