VBA:在列中选择唯一值,将它们添加到数组并将数组写入表中

Fab*_*olz 1 arrays conditional vba loops selection

我得到了一张包含各种数据的表格.在一栏中,我们发现了某种不时出现的项目编号.我想创建包含每个项目编号的列表.

所以我考虑创建一个数组并将数字添加到它中,如果现有数组中还没有它.

最后,数组应该显示在表格中

这是我到目前为止所得到的:

Sub ChoseNumbers()
' Chosing the Numbers in the AreaDim Arr() As Integer
Dim i As Integer
Dim area As Range

Set area = Columns("N").cells

i = 0
For Each cell In area
    If IsEmpty(cell) Then
        Exit For
    ElseIf i = 0 Then
        ReDim Preserve Arr(i)
        Arr(UBound(Arr)) = cell.Value
        i = i + 1
    ElseIf IsInArray(cell.Value, Arr) = False Then
        ReDim Preserve Arr(i)
        Arr(UBound(Arr)) = cell
        i = i + 1
    End If
Next cell


'Giving the selection out again

For i = 1 To (UBound(Arr))

cells(i, 1).Value = Arr(i)

Next i

End Sub
Run Code Online (Sandbox Code Playgroud)

谢谢你的建议!

B H*_*art 7

如果您要循环遍历一系列单元格,并且只是寻找一种简单有效的方法将唯一值分配给单维数组,我会查看字典对象:http: //www.w3schools.com /asp/asp_ref_dictionary.asp

Set objDic = CreateObject("Scripting.Dictionary")
For Each Cell In Area
    If Not objDic.Exists(Cell.Value) Then
        objDic.Add Cell.Value, Cell.Address
    End If
Next

I = 1
For Each Value In objDic.Keys
    Cells(I,1).Value = Value
    I = I + 1
Next
Run Code Online (Sandbox Code Playgroud)