简体   繁体   English

Excel VBA中的自定义函数,该函数在返回多个匹配值并将其组合到一个单元格的范围内查找单元格值

[英]Custom function in excel vba that lookup a cell value in a range that returns multiple match values and combine them in one cell

I'm trying to write a custom function in excel vba that lookup a cell value in a range that returns multiple match values and combine them in one cell. 我正在尝试在excel vba中编写一个自定义函数,该函数在返回多个匹配值并将它们组合到一个单元格的范围内查找一个单元格值。 it returns an error in value #VALUE . 返回值#VALUE中的错误。

I'm trying to let the user use this function, as writing a sub to do that is working fine. 我试图让用户使用此功能,因为编写一个子程序可以正常工作。

    Function LookUpMoreThanOneResult(LookUpFor As Range, LookUpAt As Range, col As Integer) As Range


Dim Findings As Range


For Each LookUpFor In LookUpFor.Cells

        For Each LookUpAt In LookUpAt.Cells

            If LookUpFor.Value = LookUpAt.Value Then

            Findings.Value = Findings.Value & vbCrLf & LookUpAt.Offset(0, col).Value
            End If


        Next LookUpAt

    Next LookUpFor

LookUpMoreThanOneResult = Findings

End Function

'below is the sub that works fine

Sub look()

Worksheets(1).Activate

Dim ref As Range

Dim arr As Range
Dim va As Range

Set ref = Range("j2:j7595")
Set arr = Worksheets(2).Range("d2:d371")

Dim r As Range
Dim a As Range


For Each r In ref.Cells

        For Each a In arr.Cells

            If r.Value = a.Value Then
            r.Offset(0, 11).Value = r.Offset(0, 11).Value & vbCrLf & a.Offset(0, 6).Value
            End If


        Next a

    Next r

End Sub

this is the answer, here i should not repeat the loop for the LookUpFor cell, and the return value of the function should be String. 这就是答案,这里我不应该为LookUpFor单元重复循环,并且函数的返回值应该为String。 so it is owrking fine now, and the user can use it. 因此现在应该可以使用了,用户可以使用它。

Function LookUpMoreThanOneResult(LookUpFor As Range, LookUpAt As Range, col As Integer) As String

Dim R As Range

        For Each R In LookUpAt

            If LookUpFor.Value = R.Value Then

            LookUpMoreThanOneResult = LookUpMoreThanOneResult & vbCrLf & R.Offset(0, col).Value
            End If

        Next R


End Function

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

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