加载仅包含唯一值的数组

时间:2011-03-21 19:12:47

标签: vba

我有一个我在VBA中循环的范围:

For Lrow = Firstrow To Lastrow Step 1
        With .Cells(Lrow, "E")
            If Not IsError(.Value) Then

            End If
        End With
    Next Lrow

在if语句中,我需要加载一个数组,每个值只有一次

MB-NMB-ILA
MB-NMB-ILA
MB-NMB-STP
MB-NMB-STP
MB-NMB-WAS
MB-NMB-WAS
MB-NMB-WAS

因此对于阵列我只想要MB-NMB-ILA,MB-NMB-STP和MB-NMB-WAS

任何人都可以帮助我,我的大脑周一不能正常工作!感谢

2 个答案:

答案 0 :(得分:1)

您可以使用过滤器来测试数组中是否存在某些内容。

Dim arr As Variant: arr = Array("test1", "test2", "test3")
If UBound(Filter(arr, "blah")) > -1 Then
    Debug.Print "it is in the array"
Else
    Debug.Print "it's not in the array"
End If

您还可以使用集合并编写子集,仅将唯一项添加到集合

Dim col As New Collection
Sub addIfUnique(sAdd As String)
    Dim bAdd As Boolean: bAdd = True
    If col.Count > 0 Then
        Dim iCol As Integer
        For iCol = 1 To col.Count
            If LCase(col(iCol)) = LCase(sAdd) Then
                bAdd = False
                Exit For
            End If
        Next iCol
    End If
    If bAdd Then col.Add sAdd
End Sub
Private Sub Command1_Click()
    Dim a As Integer
    Dim b As Integer
    For a = 1 To 10
        addIfUnique "item " & a
        For b = 1 To 10
            addIfUnique "item " & b
        Next b
    Next a
    For a = 1 To col.Count
        Debug.Print col(a)
    Next a
End Sub

答案 1 :(得分:0)

假设我在单元格A1到A5中有以下内容,并且需要一组唯一值,即{a,b,c,d}

        A
1      "a"
2      "b"
3      "c"
4      "c"
5      "d"

以下两段代码将有助于实现这一目标:

CreateUniqueArray - 从每个单元格获取val并添加到数组(如果尚未在数组中)

IsInArray - 通过执行简单循环检查数组中的值是否为实用函数

我不得不说这是蛮力的方式,并欢迎任何改进......

Sub Test()
    Dim firstRow As Integer, lastRow As Integer, cnt As Integer, iCell As Integer
    Dim myArray()
    cnt = 0
    firstRow = 1
    lastRow = 10

    For iCell = firstRow To lastRow
        If Not IsInArray(myArray, Cells(iCell, 1)) Then
            ReDim Preserve myArray(cnt)
            myArray(cnt) = Cells(iCell, 1)
            cnt = cnt + 1
        End If
    Next iCell
End Sub

Function IsInArray(myArray As Variant, val As String) As Boolean
    Dim i As Integer, found As Boolean
    found = False

    If Not Len(Join(myArray)) > 0 Then
        found = False
    Else
        For i = 0 To UBound(myArray)
            If myArray(i) = val Then
               found = True
            End If
        Next i
    End If
    IsInArray = found
End Function