簡體   English   中英

在 VBA 中使用 VLOOKUP - 通過引用不同的 VLOOKUP 或 INDEX/MATCH 來處理 N/A

[英]Using a VLOOKUP in VBA - Taking Care of N/A's by referencing a different VLOOKUP or INDEX/MATCH

我無法在 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”:類型不匹配

您無法查看整個列並按照您嘗試的方式直接將所有單元格與單個值進行比較。 要處理 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

您可以像這樣測試整個范圍:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM