设置一个在列表中包含所有 Cust_Num 的工作表,其右侧有相应的 Company Name。如下图所示:
然后,一旦您完成了所有设置,请使用 excel 中的 VLOOKUP 函数。这是我的示例公式:
=VLOOKUP(A3,LookUp!$A$1:$B$9,2,FALSE)
VLOOKUP 第一部分中的A3 是对行中Cust_Num 的单元格引用。
LookUp!$A$1:$B$9 是保存您查找值的数组。
2 会将VLOOKUP 的结果定向到第二列,在本例中为您手动输入的Company Name。
而FALSE 只会返回完全匹配的内容。
然后我只需将这个公式拖下来,我就得到了这个:
*注意:*如果您需要帮助获取列表中每个Cust_Num 的列表,您可以执行以下操作:
选择所有Cust_Num 的列表,然后在数据选项卡的功能区中,选择高级过滤器:
然后在窗口中:
- 选择
Copy To Another Location
- 输入
Copy To 范围作为查找表
- 确保选中
Unique Records Only 的复选框
然后,您只需将这些值填入对应的Company Names 一次,然后如前所述使用VLOOKUP。
如果首选 Find 方法,您可以使用:
Sub AddAllNames()
Call AddCompanyNameNextToCust_Num("37004", "Varco")
Call AddCompanyNameNextToCust_Num("44278", "Varco")
Call AddCompanyNameNextToCust_Num("44318", "Varco")
Call AddCompanyNameNextToCust_Num("12345", "Name1")
Call AddCompanyNameNextToCust_Num("12344", "Name1")
Call AddCompanyNameNextToCust_Num("12346", "Name1")
Call AddCompanyNameNextToCust_Num("98765", "Name2")
Call AddCompanyNameNextToCust_Num("56789", "Name2")
Call AddCompanyNameNextToCust_Num("89756", "Name2")
End Sub
Function AddCompanyNameNextToCust_Num(strCust_Num As Variant, strCompanyName As String)
Dim rngCust_nums As Range, rngFoundCell As Range, rngFirstCellFound As Range
Dim rngCust_NumsColumn As Long
Dim boolFinished As Boolean
'Get Column With header "cust_num"
rngCust_NumsColumn = WorksheetFunction.Match("cust_num", Rows(1), 0)
'Set The Search range to column from last line
Set rngCust_nums = ActiveSheet.Columns(rngCust_NumsColumn)
'Get the first matching value of Cust_Num (passed into sub)
Set rngFoundCell = rngCust_nums.Find(What:=strCust_Num, LookIn:=xlValues, _
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
'Check to make sure a match was found/ "Not Nothing"
If Not rngFoundCell Is Nothing Then
'Save the First Found Cell
Set rngFirstCellFound = rngFoundCell
'Add Company Name One Column to the Right of First Found Cust_Num
rngFoundCell.Offset(, 1).Value = strCompanyName
'Start Looping a "FindNext"
Do While boolFinished = False
'Set each new match into an overwriting Variable
Set rngFoundCell = rngCust_nums.FindNext(After:=rngFoundCell)
'Make sure the match is "Something"
If Not rngFoundCell Is Nothing Then
'Make sure We have not gone through the whole list and that we
'are not back to the begining
If rngFoundCell.Address = rngFirstCellFound.Address Then Exit Do
'If a new match is found and is not the starting point then add
'the company name in the next column
rngFoundCell.Offset(, 1).Value = strCompanyName
Else
'When nothing is Found End loop
boolFinished = True
End If
Loop
Else 'If not even one match was found
MsgBox strCust_Num & " not Found"
End If
End Function