简体   繁体   English

VBA函数用唯一的拆分条目填充列

[英]VBA Function to fill column with split entries that are unique

I am in need of help creating a very specific VBA function. 我需要帮助来创建非常具体的VBA功能。 I need a function that will both split a cell's values and populate another column with unique values. 我需要一个既可以拆分单元格的值,又可以用唯一值填充另一列的函数。

I am currently using =IFERROR(INDEX(List,MATCH(0,INDEX(COUNTIF($A$1:A2,List),0,0),0)),"") in order to get unique values out of one column to another. 我目前正在使用=IFERROR(INDEX(List,MATCH(0,INDEX(COUNTIF($A$1:A2,List),0,0),0)),"")以便从一列中获取唯一值到另一个。 Unfortunately, some of these values will be concatenated with a "," but still need to be unique. 不幸的是,其中一些值将与“,”连接,但仍需要唯一。

Unfortunately, my knowledge of VBA is far from extensive. 不幸的是,我对VBA的了解还远远不够。 Does anyone have any suggestions? 有没有人有什么建议?

Say we have data like: 假设我们有以下数据:

在此处输入图片说明

In column A . A栏中。 Running this macro will extract uniques and put then in column B : 运行此宏将提取唯一性,然后放入B列:

Sub dural()
    Dim c As Collection, K As Long
    Set c = New Collection
    K = 1
    On Error Resume Next
    For Each r In Range("A1:A" & Cells(Rows.Count, "A").End(xlUp).Row)
        ary = Split(r.Text, ",")
        For Each a In ary
            c.Add a, CStr(a)
            If Err.Number = 0 Then
                Cells(K, "B").Value = a
            K = K + 1
            Else
                Err.Number = 0
            End If
        Next a
    Next r
    On Error GoTo 0
End Sub

在此处输入图片说明

EDIT#1: 编辑#1:

Here is the same logic in UDF form: 这是UDF形式的相同逻辑:

Public Function UniKues(rIn As Range)
    Dim c As Collection, K As Long
    Set c = New Collection
    K = 1
    On Error Resume Next
    For Each r In rIn
        ary = Split(r.Text, ",")
        For Each a In ary
            c.Add a, CStr(a)
        Next a
    Next r

    ReDim bry(1 To c.Count, 1 To 1)
    For i = 1 To c.Count
        bry(i, 1) = c.Item(i)
    Next i
    UniKues = bry
    On Error GoTo 0

End Function

在此处输入图片说明

Just hi-light a section of column B and enter the UDF in Array form 只需突出显示B列的一部分,然后以Array形式输入UDF

EDIT#2 编辑#2

Here is the UDF with chris neilsen's suggestions: 这是带有chris neilsen的建议的UDF

Public Function UniKues(rIn As Range)

    Dim c As Collection, K As Long, MM As Long
    Dim CC As Long
    Set c = New Collection
    K = 1
    On Error Resume Next
    For Each r In rIn
        ary = Split(r.Text, ",")
        For Each a In ary
            c.Add a, CStr(a)
        Next a
    Next r
    MM = Application.Caller.Rows.Count
    CC = c.Count
    dimn = Application.WorksheetFunction.Max(MM, CC)
    ReDim bry(1 To dimn, 1 To 1)
    For i = 1 To CC
        bry(i, 1) = c.Item(i)
    Next i
    If MM > CC Then
        For i = CC + 1 To MM
            bry(i, 1) = ""
        Next i
    End If
    UniKues = bry
    On Error GoTo 0

End Function

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM