checking if value present in array

后端 未结 3 1895
醉话见心
醉话见心 2021-01-13 19:28

I\'m using a function from this question, however, it doesn\'t seem to work in my case.

Basically, this script is going through a column selecting distinct values an

3条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-13 20:07

    Here is how I would do it for a one-dimensional array, using the Application.Match function, instead of another UDF.

    I have consolidated some of your If/ElseIf logic with a Do...While loop, and then use the Match function to check whether cell value exists in the array. If it does not exist, then add it to the array and continue to the next cell in your range.

    Sub SelectDistinct()
    
    Dim arr() As String
    Dim i As Integer
    Dim cells As Range
    Dim cl As Range
    Dim foundCl As Boolean
    
        Set cells = Worksheets("Sheet6").Columns(1).cells
    
        Set cl = cells.cells(1)
    
        Do
            If IsError(Application.Match(cl.Value, arr, False)) Then
                ReDim Preserve arr(i)
                arr(i) = cl
                i = i + 1
            Else:
                'Comment out the next line to completely ignore duplicates'
                MsgBox cl.Value & " already exists!"
    
            End If
    
            Set cl = cl.Offset(1, 0)
        Loop While Not IsEmpty(cl.Value)
    
    End Sub
    

提交回复
热议问题