VBA代码可扫描单元格中逗号分隔的值并检索查找值

时间:2018-12-03 16:03:35

标签: excel vba excel-vba

我有一种情况,我必须通读逗号分隔的一个单元格中的值,并且仅从该数组中检索值以与特定的查找值匹配。例如:

enter image description here

所以我需要的是一个从第2行“链接”列中检索所有任务(或其他可能有所不同的问题类型)的功能

预期结果:针对A2,我想检索A4和A6

3 个答案:

答案 0 :(得分:1)

这是我修改过的内容,因此您可以将其自定义为任何查找值

函数GetLinkedItem(链接为字符串,targetLinkType为字符串) Dim temp(0到0)作为字符串     GetLinkedItem =“无”     如果Trim(link)=“”然后退出函数

Dim links() As String, i As Long
links = Split(link, ",")
For i = 0 To UBound(links)
    'select the links that are targetLinkType
    Dim j As Long

    j = GetRow(Trim(links(i)))

    If Sheets("Data").Cells(j, ISUUETYPE_COL) = targetLinkType Then

        temp(0) = temp(0) & " " & Sheets("Data").Cells(j, ID_COL) & ","

    End If
   GetLinkedItem = Join(temp, ",")
   Next i

结束功能

答案 1 :(得分:0)

您可以创建UDF来执行此查找。在VBE中的新模块中,粘贴以下内容:

Function getTasks(tasklist As Range, availabletasks As Range) As String
    'tasklist is the incoming array in Column C
    'availabletasks is the stuff in Column A

    'Array for output
    Dim tasks() As String: ReDim tasks(0 To 0)

    'Loop through each item in taslist using an array
    For Each task In Split(tasklist.Value, ", ")

        'Search availabletasks
        If Not availabletasks.Find(task) Is Nothing Then
            'pop the array
            If tasks(0) <> "" Then ReDim Preserve tasks(0 To UBound(tasks) + 1)
            tasks(UBound(tasks)) = task
        End If
    Next

    'Return what we found
    getTasks = Join(tasks, ", ")

End Function

现在,在电子表格中,您可以像常规公式一样使用此功能:

=getTasks(C1,$A$1:$A$6) 

C1的列表类似于A4, A25, A22, A6, A29, A42$A$1:$A$6,就像您的示例列A。这将返回A4, A6

enter image description here

答案 2 :(得分:0)

非常感谢。我在新模块中添加了代码,并将该函数用作公式。我得到的只是1个值而不是2个值(仅获得A4而不是A6)。 enter image description here