从Range获取唯一值 - 如何删除单元格中的#N / A值

时间:2016-08-01 02:59:10

标签: vba excel-vba excel

我有这段代码可以从B列获取唯一值。

Dim lastrow as Long
dim var2 as variant
dim obj2 as Object
set obj2 = CreateObject("Scripting.Dictionary")
lastRow = Cells(Rows.count, 3).End(xlUp).Row
    var2 = Application.Transpose(Range([B2], Cells(Rows.count, "B").End(xlUp)))

    For lastRow = 2 To UBound(var2, 1)
        obj2(var2(lastRow)) = 1

    Next
    Range("C1:C" & obj.count) = Application.Transpose(obj2.keys)

我有这些数据:

enter image description here

然后我会在C列中粘贴唯一值。但是C列中的输出包含值#N/A。有没有办法排除C列中显示的#N/A

1 个答案:

答案 0 :(得分:1)

在制作源Dictionary的副本后,您可以使用RemoveDuplicates Range方法来实现目标,而不是使用Range。例如:

Option Explicit

Sub Test()

    Dim rngSource As Range
    Dim rngTarget As Range

    Set rngSource = Sheet1.Range("B2", Sheet1.Range("B2").End(xlDown))
    Set rngTarget = Sheet1.Range("C2")

    CopyUniqueValues rngSource, rngTarget

End Sub

Sub CopyUniqueValues(rngSource As Range, rngTarget As Range)

    'copy source to target
    rngSource.Copy rngTarget

    'extend target range
    Set rngTarget = rngTarget.Resize(rngSource.Rows.Count, 1)

    'remove duplicates
    rngTarget.RemoveDuplicates Columns:=1, Header:=xlNo

End Sub