我希望用户输入用户名并进行搜索,然后搜索将导致将其关联数据从另一个电子表格输出到他们搜索的电子表格中。我知道我需要一个带有vlookup的循环,但是我不知道如何构造它。
我已经开发了查找用户所需的vlookup,它输出了他们的数据,但是只有一行,并且用户可能有8行与他们的信息相关联。
Dim wfUser As String
wfSAP = Application.WorksheetFunction.VLookup(uc, Range("wfData"), 1, False)
Dim wfRole As String
wfRole = Application.WorksheetFunction.VLookup(uc, Range("wfData"), 2, False)
With Range("userData")
.Offset(0, 0) = wfUser
.Offset(0, 1) = wfRole
End With
End If
它只会查找用户名的第一个匹配项,并记录该用户名,而不是与用户名关联的所有行
答案 0 :(得分:0)
尝试一下:
Sub lookupData()
'https://stackoverflow.com/questions/56587450/lookup-and-record-multiple-entries-with-the-same-name-from-a-spreadsheet
Dim arrWfData As Variant: arrWfData = Range("wfData") 'allocate the data to an array
Dim R As Long, X As Long
For R = LBound(arrWfData) To UBound(arrWfData) 'for each row in the array
If arrWfData(R, 1) = uc Then 'if it matches with <uc>
With Range("userData") 'allocate the values
.Offset(X, 0) = arrWfData(R, 1)
.Offset(X, 1) = arrWfData(R, 2)
End With
X = X + 1
End If
Next R
End Sub
答案 1 :(得分:0)
我正在猜测您的某些变量,因为它们不匹配或未在您提供的示例中定义,但请尝试如下操作:
Dim wfArr(), uc As String, i As Long, f As Integer
f = 0
uc = "User"
'load your wfData range to an array
wfArr = Range("wfData").Value
'loop through the array to find all occurances of specified user
For i = LBound(wfArr, 1) To UBound(wfArr, 1)
'if the user matches, write the values to userData Range
If wfArr(i, 1) = uc Then
Range("userData").Offset(f, 0) = uc
Range("userData").Offset(f, 1) = wfArr(i, 2)
f = f + 1
End If
Next i