在VBA中使用VLOOKUP – 通过引用不同的VLOOKUP或INDEX / MATCH来照顾N / A

我无法弄清楚这个在VBA中的IF-THEN语句。 我正在使用的代码使用VLOOKUP将值拉入列E,但是一些结果作为#N / A进来,因为它们不包含VLOOKUP所引用的选项卡。 如果结果出现#N / A,我需要VBA在我的工作簿中另一个选项卡上执行另一个查找(最好是索引/匹配)。 这是我到目前为止,第6步完美,但返回一些N / A的。 错误来自第7步,因为我试图用IF-THEN语句来解决N / A:

'Step 6: Copy the recordset to Excel With ThisWorkbook.Worksheets("DQ_Collectors_3162") .Activate .Range("A2:R" & Rows.Count).Clear .Range("A2").CopyFromRecordset rs 'Dealer column Dim dealerCol As String Dim FinalRow As Integer Dim contractCol As String contractCol = ConvertToLetter(FindMatchingValueColumn("Contract ID", 1)) FinalRow = .Cells(Application.Rows.Count, 1).End(xlUp).Row + 1 lookup = "=VLOOKUP(" & contractCol & ":" & contractCol & ",'Dealer Name Index'!A:B,2,FALSE)" dealerCol = ConvertToLetter(FindMatchingValueColumn("Dealer", 1)) .Range(dealerCol & "2").Value = vlookup .Range(dealerCol & "2:" & dealerCol & FinalRow).FillDown .Range(dealerCol & ":" & dealerCol).Copy End With 'Step 7: Take Care of N/A's Dim R As Range indexmatch = "=INDEX('IBIC Name Index'B:B,match(B:B,'IBIC Name Index'A:A,0))" Set R = Range("E:E") If R.Value = "#N/A" Then R.Value = indexmatch End If 

我得到的错误是 – 运行时错误“13”:types不匹配

你可以像这样testing整个范围:

If WorksheetFunction.CountIf(R,"#N/A") > 0 Then

您不能查看整个列,并直接将所有单元格与您尝试的方式进行比较。 要处理E列中的所有#NA错误,请使用SpecialCells。

 Dim r As Range With Worksheets("Sheet5") With Intersect(.UsedRange, .Range("E:E")) For Each r In .SpecialCells(xlCellTypeFormulas, xlErrors) If r.Value = CVErr(xlErrNA) Then Debug.Print r.Address & " is an #NA error" End If Next r End With End With