【问题标题】:VBA - Adding unique values to existing arrayVBA - 向现有数组添加唯一值
【发布时间】:2018-11-20 22:01:51
【问题描述】:

假设我有两个单独的列/数组。

A 列有 100 行,每行有 20 长的字符串

A(1)=daskjdkjasdj

A(2)=asdsadgggggg

A(3)=dsadpoeeeeee

B 列是一列有 200 行,其中一些行的值与上面提到的相同,我想添加唯一的。 仅当它不属于 A 列时,我才想添加新标识符。 (我忘了提到,对于带有标识符的每一行,还有 20 个其他列的数据也应该添加。我很抱歉)

我想将标识符不在数据 A 中的数据 B 中的行添加到数据 A。 结果我会得到 ​​p>

我只是这样做了:

for i = 1 to lastrow_column_b
    g=0
    for j=1 to ubound(column_a)
        if column_a(j)=cells(i) then g=1
        goto skip
    next
    skip:
    if g = 0 then "do something, add to column_a"
next

但我相信有更有效的方法来做到这一点

【问题讨论】:

  • 将 A 列读入 Scripting.Dictionary。然后沿着 B 列向下并添加尚不存在的项目。 2 个集合的联合将是 .Keys
  • 这确实需要有代表性的样本数据和预期的结果。

标签: arrays excel vba unique


【解决方案1】:

下面的代码应该让您走上正轨。第一个循环将 A 列中的所有条目添加到数组中。第二个循环仅添加来自 C 列的新条目。输出将粘贴到 E 列。您应该能够更改引用以满足您的需要。希望对您的任务有所帮助。

Sub UpdateColumn()
    Dim objDict As Object
    Dim key As Variant,


    ' Create new collection
    Set objDict = CreateObject("System.Collections.ArrayList")

    With ThisWorkbook.ActiveSheet
        With .Range("A2", .Range("A" & .Rows.Count).End(xlUp))
            ' Read data of column A into array
            ' Does not check for duplicates
            For Each key In .Value
                objDict.Add key
            Next
        End With

        With .Range("C2", .Range("C" & .Rows.Count).End(xlUp))
            ' Read data of column B into array, add new entries only
            For Each key In .Value
                If Not objDict.Contains(key) Then objDict.Add key
            Next
        End With

        .Range("E2").Resize(objDict.Count) = Application.Transpose(objDict.toarray())

    End With

End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-15
    • 2021-12-27
    • 2013-02-21
    • 1970-01-01
    • 2018-02-20
    相关资源
    最近更新 更多