簡體   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

我正在嘗試在excel vba中編寫一個自定義函數,該函數在返回多個匹配值並將它們組合到一個單元格的范圍內查找一個單元格值。 返回值#VALUE中的錯誤。

我試圖讓用戶使用此功能,因為編寫一個子程序可以正常工作。

    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

這就是答案,這里我不應該為LookUpFor單元重復循環,並且函數的返回值應該為String。 因此現在應該可以使用了,用戶可以使用它。

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