我正在使用以下代码使用VBA对另一个工作簿执行vlookup。 它没有任何问题,但现在我不仅希望看到一个单元格,而且还要遍历一个范围。比方说T15:T200。
任何可以帮助修改代码的人都可以这样做吗?
Sub VlookMultipleWorkbooksBACKUP()
Dim lookFor As Range
Dim srchRange As Range
Dim book1 As Workbook
Dim book2 As Workbook
Dim book2Name As String
book2Name = "testbog.xlsx"
Dim book2NamePath As String
book2NamePath = ThisWorkbook.Path & "\" & book2Name
Set book1 = ThisWorkbook
If IsOpen(book2Name) = False Then Workbooks.Open (book2NamePath)
Set book2 = Workbooks(book2Name)
Set lookFor = book1.Sheets(1).Cells(15, 20) ' value to find
Set srchRange = book2.Sheets(1).Range("A:B") 'source
lookFor.Offset(0, 20).Value = Application.Vlookup(lookFor, srchRange, 2, False)
End Sub
谢谢!
答案 0 :(得分:2)
只需在代码的最后部分包含一个循环,并使用循环计数器变量而不是15
:
'...
Set book2 = Workbooks(book2Name)
Set srchRange = book2.Sheets(1).Range("A:B") 'source
Dim r As Long
For r = 15 To 200
Set lookFor = book1.Sheets(1).Cells(r, 20) ' value to find
lookFor.Offset(0, 20).Value = Application.Vlookup(lookFor, srchRange, 2, False)
Next
End Sub