我正在尝试使用WorksheetFunction对vlookup进行编码,以在Excel(要搜索的动态单元格和要输入结果的动态单元格)中照常执行vlookup。
Sub vlookupFunction()
Dim cl As Range
Dim searchManagersRange As Range
Dim rangeToSearchManagers As Range
Dim lastRow As Long
lastRow = ThisWorkbook.Sheets(1).Cells(Rows.Count, 1).End(xlUp).Row
Set rangeToSearchManagers = ThisWorkbook.Sheets(1).Range("A2:A" & lastRow)
Set searchManagersRange = ThisWorkbook.Sheets(3).UsedRange
For Each cl In rangeToSearchManagers
On Error GoTo managerNotFound
ThisWorkbook.Sheets(1).Range(cl.Offset(0, 16).Address) = WorksheetFunction.VLookup(cl, searchManagersRange, 2, 0)
Next cl
managerNotFound:
cl.Offset(0, 16).Value = "#N/A"
Resume Next
End Sub
代码工作正常并完成了搜索,但是最后它返回未设置的对象变量...错误,因为cl最终是“ Nothing”。
答案 0 :(得分:0)
使用You need to press Alt+6 twice to restart the logcat window. That way it'll show the log outputs.
Go to your sdk Folder --> Platform tools --> adb click 2 times
using this adb server restart again
代替Application
,您可以在不“引发”错误的情况下“捕获”错误,并删除凌乱的On Error / Resume语句。
阅读例如this,以获得更多信息。
Worksheetfunction
答案 1 :(得分:0)
您可以避免使用Loop
Option Explicit
Sub test()
With ThisWorkbook.Sheets(1)
.Range("Q2:Q" & .Cells(.Rows.Count, "A").End(xlUp).Row).Formula = "=IFERROR(VLOOKUP(A2," & ThisWorkbook.Sheets(3).Name & "!" & ThisWorkbook.Sheets(3).UsedRange.Address & ",2,0),"""")"
End With
End Sub