giao dien magazine

Lọc danh sách bằng vba

Có những lúc chúng ta cần phải lấy ra một danh sách từ một danh sách có rất nhiều dữ liệu trùng nhau.
Người ta thường gọi đây là lọc trùng lặp, có rất nhiều cách có thể làm trong trường hợp này như dùng chức năng filter để làm. Tuy nhiên để "bờ rồ" hơn thì dùng code để thấy được nó vi diệu đến dường nào.
Hãy cùng khám phá cách thực hiện với code dưới đây.

Dưới đây là code vba để lọc ra danh sách đó.

Sub LocDuLieu_Duynhat()

    Dim vaData As Variant

    Dim colUnique As Collection

    Dim aOutput() As Variant

    Dim i As Long

    Dim LastRow As Long

    LastRow = Worksheets(Sheet1.Name).Cells(2, "A").End(xlDown).Row


    'Lay du lieu can loc dua vao mang

    vaData = Sheet1.Range("A2:G" & LastRow).Value

    'Create a new collection

    Set colUnique = New Collection

    'Loop through the data

    For i = LBound(vaData, 1) To UBound(vaData, 1)

        'Collections can't have duplicate keys, so try to

        'add each item to the collection ignoring errors.

        'Only unique items will be added

        On Error Resume Next

            colUnique.Add vaData(i, 1), CStr(vaData(i, 1))

        On Error GoTo 0

    Next i

    'size an array to write out to the sheet

    ReDim aOutput(1 To colUnique.Count, 1 To 1)

    'Loop through the collection and fill the output array

    For i = 1 To colUnique.Count

        aOutput(i, 1) = colUnique.Item(i)

    Next i

    'Write the unique values to column B

    Sheet1.Range("B2").Resize(UBound(aOutput, 1), UBound(aOutput, 2)).Value = aOutput

End Sub



No comments:
Write nhận xét