使用单元格中的部分数据在单独的工作表上查找ID

时间:2017-04-19 17:26:29

标签: excel excel-vba vba

Sheet 1中

foo.exe

Sheet 2中

|Header1|Header3|
|L/F M  |Blank  |
|L/F M  |Blank  |
|L/F M  |Blank  |
|L/F M  |Blank  |
|L/F M  |Blank  |
|L/F M  |Blank  |

目标是运行一个脚本,该脚本将从sheet1获取名字或姓氏,并与sheet2中的相应名称进行比较。找到匹配项后,它会将ID值放在旁边的空白单元格中。

|Header1|Header2|
|ID     |F L    |
|ID     |F L    |
|ID     |F L    |
|ID     |F L    |
|ID     |F L    |
|ID     |F L    |

F = First Name
M = Middle Name
L = Last Name

我一直试图调整此代码,但没有成功。

1 个答案:

答案 0 :(得分:0)

如果你的表1看起来像这样:

Miller/John Brent
Acme/Joan Alice
Jones/Beatrice Sally

你的表2看起来像这样

ID 101  John Miller
ID 102  Joan Acme
ID 103  Beatrice Jones

然后,以下代码可以帮助您学习拆分功能。一旦您学习了如何从表1中获取名字和姓氏,您就可以在sheet2上搜索它并获得相应的ID号

Sub getID()

Dim ws1 As Worksheet, ws2 As Worksheet
Dim arraySheet2, arraySheet1_a, arraySheet1_b

Set ws1 = Worksheets("Sheet1")
Set ws2 = Worksheets("Sheet2")

For i = 1 To 3
    arraySheet1_a = Split(ws1.Range("A" & i).Value, "/")
    arraySheet1_b = Split(arraySheet1_a(1), " ")
Debug.Print arraySheet1_b(0) & " " & arraySheet1_a(0)
Next i

Debug.Print "   "


For i = 1 To 3
    arraySheet2 = Split(ws2.Range("B" & i).Value, " ")
Debug.Print arraySheet2(0) & " " & arraySheet2(1)
Next i

Set ws1 = Nothing
Set ws2 = Nothing

End Sub