你可以使用VBA版函数Application.VLookup。
下面的代码检查工作表“Microsoft”中单元格 B21 的值是否在工作表“SN 用户名”的 A:B 列中找到。如果找到它,它将第二列返回到单元格 A21(您可以根据需要对其进行修改)。如果没有,它会在单元格 A21 中放置一条“未找到项目”的文本消息 - 仅供参考。
Option Explicit
Sub VLookup_withErrHandling()
Dim Cell As Range
Dim Rng As Range
Dim lRow As Range
Set Cell = Sheets("Microsoft").Range("B21")
Set Rng = Sheets("SN Username").Range("A:B")
If Not IsError(Application.VLookup(Cell, Rng, 2, False)) Then
Cell.Offset(0, -1).Value = Application.VLookup(Cell, Rng, 2, False)
Else
Cell.Offset(0, -1).Value = "Item Not Found"
End If
End Sub
添加For 循环:如果您想循环遍历“Microsoft”工作表中的许多行,可以添加以下代码:
Dim lRow As Long
' just for example, loop from row 21 until row 30
For lRow = 21 To 30
Set Cell = Sheets("Microsoft").Range("B" & lRow)
If Not IsError(Application.VLookup(Cell, Rng, 2, False)) Then
Cell.Offset(0, -1).Value = Application.VLookup(Cell, Rng, 2, False)
Else
Cell.Offset(0, -1).Value = "Item Not Found"
End If
Next lRow
编辑 1:根据PO修改说明如下:
Option Explicit
Sub VLookup_withErrHandling()
Dim Cell As Range
Dim Rng As Range
Dim LastRow As Long
Dim lRow As Long
With Sheets("SN Username")
' find last row with username in column A
LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
Set Rng = Sheets("SN Username").Range("A2:B" & LastRow)
End With
' loop through row 2 until row 20
For lRow = 2 To 20
Set Cell = Sheets("Microsoft").Range("A" & lRow)
If Not IsError(Application.VLookup(Cell.Value, Rng, 2, False)) Then
Cell.Offset(0, 1).Value = Application.VLookup(Cell.Value, Rng, 2, False)
Else
Cell.Offset(0, 1).Value = "UserName Not Found in SN UserNames sheet"
End If
Next lRow
End Sub