从列表中提取唯一值

时间:2010-10-28 17:57:51

标签: excel vba excel-vba

我有以下代码返回50个随机颜色编码的数字:

Sub RandomNumberColor()
  Dim Numbers, i As Integer
  Dim MyRange As Range

  Set MyRange = Worksheets("Rnd").Range("A1:A50")

  For i = 1 To MyRange.Rows.Count
    Numbers = Int((10 - 1 + 1) * Rnd + 1)
    Worksheets("Rnd").Cells(i, 1) = Numbers
    Worksheets("Rnd").Cells(i, 1).Interior.ColorIndex = Worksheets("Rnd").Cells(i, 1).Value
  Next i

End Sub

我试图找到一种方法来查找该列(A)中的所有唯一值,并将它们返回到列(B)。出于某种原因,我遇到了解决这个问题的问题,任何帮助都会非常感激!

2 个答案:

答案 0 :(得分:6)

Sub FindUniqueValues(SourceRange As Range, TargetCell As Range)
    SourceRange.AdvancedFilter Action:=xlFilterCopy, _
        CopyToRange:=TargetCell, Unique:=True
End Sub

答案 1 :(得分:0)

你可以修剪一些这样的线条,但以下是诀窍 在第一个循环中,我们填充只有唯一RandNum值的字典(哈希表),然后我们迭代该字典。

Sub RandomNumberColor()
    Dim RandNum As Integer
    Dim i As Integer
    Dim MyRange As Range

    Set dict = CreateObject("Scripting.Dictionary")

    Set MyRange = Worksheets("Rnd").Range("A1:A50")

    For i = 1 To MyRange.Rows.Count
        RandNum = Int((10 - 1 + 1) * Rnd + 1)
        Worksheets("Rnd").Cells(i, 1) = RandNum
        Worksheets("Rnd").Cells(i, 1).Interior.ColorIndex = _
        Worksheets("Rnd").Cells(i, 1).Value

        If Not dict.Exists(RandNum) Then
            dict.Add RandNum, RandNum
        End If
    Next i

    i = 1
    For Each key In dict.Keys()
        Worksheets("Rnd").Cells(i, 2) = dict(key)
        i = i + 1
    Next

    Set dict = Nothing
    Set MyRange = Nothing
End Sub