如何使用2D数组?

时间:2017-11-17 17:53:46

标签: vba

我已经使用i和j数组来保存值,有没有办法通过使用多维数组合或两种方式压缩?

Dim iArray 
Dim jArray
With wks.Range("B2:B" & p)
    iArray = .Value
End With 
With CreateObject("scripting.dictionary")
.comparemode = 2
    For Each item In iArray
        If Not .exists(item) Then
        .Add item, Nothing
        End If
    Next
        If .Count Then
            Me.Search1.List = Application.Transpose(.keys)
        End If
End With

With wks.Range("c2:c" & p)
    jArray = .Value
End With 
With CreateObject("scripting.dictionary")
.comparemode = 1
    For Each item In jArray
        If Not .exists(item) Then
        .Add item, Nothing
        End If
    Next
        If .Count Then
            Me.Search2.List = Application.Transpose(.keys)
        End If
End With

1 个答案:

答案 0 :(得分:0)

您应该考虑将该功能提取到一个独立的子域,您可以使用参数单元格

Sub ListUniquesFromRange(rng As Range, lst As Object)
    Dim iArray, v
    If rng.Columns.Count > 1 Then
        MsgBox "single-column range only!", vbCritical
        Exit Sub
    End If
    iArray = rng.Value
    With CreateObject("scripting.dictionary")
        .comparemode = 2
        For Each v In iArray
            If Not .exists(v) Then .Add v, Nothing
        Next
        If .Count Then
            lst.List = Application.Transpose(.keys)
        End If
    End With
End Sub

然后你可以这样做:

ListUniquesFromRange wks.Range("B2:B" & p), Me.Search1
ListUniquesFromRange wks.Range("C2:C" & p), Me.Search2