[英]Excel, VBA Vlookup, multiple returns into rows
對VBA來說還很陌生,所以請原諒我的無知。
您將如何更改下面的代碼以將結果返回到行而不是字符串?
提前致謝....
數據
Acct No CropType
------- ---------
0001 Grain
0001 OilSeed
0001 Hay
0002 Grain
功能
=vlookupall("0001", A:A, 1, " ")
這是代碼:
Function VLookupAll(ByVal lookup_value As String, _
ByVal lookup_column As range, _
ByVal return_value_column As Long, _
Optional seperator As String = ", ") As String
Application.ScreenUpdating = False
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
Application.ScreenUpdating = True
End FunctionNotes:
嘗試這個:
Option Explicit
Function VLookupAll(ByVal lookup_value As String, _
ByVal lookup_column As Range, _
ByVal return_value_column As Long) As Variant
Application.ScreenUpdating = False
Dim i As Long, _
j As Long
Dim result() As Variant
ReDim result(1 To Application.Caller.Rows.Count, 1 To 1) As Variant
j = LBound(result)
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 j > UBound(result, 1) Then
Debug.Print "More rows required for output!"
Exit For
End If
result(j, 1) = lookup_column(i).Offset(0, return_value_column).Text
j = j + 1
End If
End If
Next
VLookupAll = result
Application.ScreenUpdating = True
End Function
現在,在工作表上輸入公式時,選擇三個單元格,一個在另一個單元格上方,然后鍵入以下內容:
=vlookupall("0001",$A:$A, 1, " ")
然后按ctrl + shift + enter輸入公式。
請注意,如果您選擇的輸出行太少,您的即時窗口(在vb編輯器中按ctrl + g)將顯示一條消息“輸出需要更多行!”。 我把它作為一個消息框,但是由於它具有自動計算功能,所以有點瘋狂。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.