Excel VLookup具有多个结果,但没有重复

时间:2018-01-23 00:58:15

标签: excel vba vlookup

this question中,由answer撰写的最高投票(最佳)aevanko(请参阅下面的代码)有效,但它不会考虑重复值 - 它只包含多个值次。

如何调整此功能以仅显示不同的值/结果?

Function VLookupAll(ByVal lookup_value As String, _
                    ByVal lookup_column As range, _
                    ByVal return_value_column As Long, _
                    Optional seperator As String = ", ") As String

Dim i As Long
Dim result As String

For i = 1 To lookup_column.Rows.count
    If Len(lookup_column(i, 1).text) <> 0 Then
        If lookup_column(i, 1).text = lookup_value Then
            result = result & (lookup_column(i).offset(0, return_value_column).text & seperator)
        End If
    End If
Next

If Len(result) <> 0 Then
    result = Left(result, Len(result) - Len(seperator))
End If

VLookupAll = result

End Function

1 个答案:

答案 0 :(得分:2)

为避免在结果字符串中添加内容(如果字符串中已存在),只需在添加之前检查它是否已存在于字符串中:

Function VLookupAll(ByVal lookup_value As String, _
                    ByVal lookup_column As range, _
                    ByVal return_value_column As Long, _
                    Optional separator As String = ", ") As String

    Dim i As Long
    Dim result As String

    For i = 1 To lookup_column.Rows.count
        If Len(lookup_column(i, 1).text) <> 0 Then
            If lookup_column(i, 1).text = lookup_value Then
                If Instr(separator & result & separator, _
                         separator & lookup_column(i).Offset(0, return_value_column).Text & separator) = 0 Then
                    result = result & lookup_column(i).Offset(0, return_value_column).Text & separator
                End If
            End If
        End If
    Next

    If Len(result) <> 0 Then
        result = Left(result, Len(result) - Len(separator))
    End If

    VLookupAll = result

End Function

只有使用非空白分隔符时,这才能可靠地工作,并且您的数据实际上都不包含分隔符。

如果您希望将具有相同价值的不同案例(例如&#34; ABC&#34;和&#34; Abc&#34;)视为&#34;重复&#34;,则需要更改来自

If声明
If Instr(separator & result & separator, _
         separator & lookup_column(i).Offset(0, return_value_column).Text & separator) = 0 Then

If Instr(separator & LCase(result) & separator, _
         separator & LCase(lookup_column(i).Offset(0, return_value_column).Text) & separator) = 0 Then

但是您对查找值的测试(即If lookup_column(i, 1).text = lookup_value Then)目前区分大小写,因此您可能不希望重复&#34;重复&#34;通过不区分大小写的匹配检测到。