【问题标题】:Custom function in excel vba that lookup a cell value in a range that returns multiple match values and combine them in one cellexcel vba中的自定义函数在返回多个匹配值的范围内查找单元格值并将它们组合在一个单元格中
【发布时间】:2015-11-08 03:30:54
【问题描述】:

我正在尝试在 excel vba 中编写一个自定义函数,该函数在返回多个匹配值的范围内查找单元格值并将它们组合在一个单元格中。 它返回值 #VALUE 中的错误。

我正在尝试让用户使用此功能,因为编写一个 sub 来做到这一点工作正常。

    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

【问题讨论】:

  • 我猜ReturnedValueRange 不是单个单元格,而是某个范围,您希望提取与匹配单元格具有相同行的单元格 (?)。

标签: excel vba


【解决方案1】:

这就是答案,这里我不应该重复 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多