我对VBA非常陌生,任何帮助都将不胜感激。我正在尝试创建一个宏来执行vlookup,而不是在单元格中手动输入它。
我的excel文件有两个工作表,一个叫做'Microsoft‘,另一个叫做'SN用户名’。
因此,我在“SN用户名”中查找数据,查找返回到工作表“Microsoft”(B21)的结果。
下面是在VBA = vlookup (B21,'SN用户名‘!a:B,2,FALSE)中尝试执行的VLOOKUP
任何帮助都将不胜感激!谢谢
发布于 2016-11-15 11:50:32
您可以使用VBA版本函数Application.VLookup。
下面的代码段检查工作表"Microsoft“中单元格B21的值是否在工作表"SN用户名”中的A:B列中。如果找到它,它将返回第二列到单元格A21 (您可以根据需要修改它)。如果没有,它会在单元格A21中添加一条"Item not“的文本消息--仅供参考。
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 SubFor 添加了一个循环:如果您想遍历"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 Subhttps://stackoverflow.com/questions/40608786
复制相似问题