![](/img/trans.png)
[英]Using excel VBA to lookup cell value, and return multiple values based on that cell
[英]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.