尽管有COUNTIF显示匹配项,但WorksheetFunction.VLookup找不到匹配项

时间:2020-03-31 14:51:58

标签: excel vba

我正在处理一段代码,我从一个选项卡中获取了信息,现在需要匹配另一个选项卡中的信息。在“发票电子表格”标签上,我创建了一个与以下“匹配测试”顺序相同的串联字段,没有空格或标点符号。

我在另一个地方使用了相同代码的变体,但效果很好,但是由于某种原因,它在这里不起作用。 COUNTIF函数发现结果存在,但我无法匹配它。

我尝试在不使用范围变量InvoiceRng的情况下运行此程序,而仅将其放在该范围内。但是我不断收到错误1004,找不到匹配项。当我多次成功使用这种相似的布局时,有什么想法为什么这段代码无法在本节中使用?

Set InvoiceRng = Sheets("Invoice Spreadsheet").Range("A3:AG" & LRInvoice)

If Application.WorksheetFunction.CountIfs( _
      Sheets("Invoice Spreadsheet").Range("I3:I" & LRInvoice), InvItem, _
      Sheets("Invoice Spreadsheet").Range("Y3:Y" & LRInvoice), InvBill, _
      Sheets("Invoice Spreadsheet").Range("Z3:Z" & LRInvoice), InvShip, _
      Sheets("Invoice Spreadsheet").Range("AA3:AA" & LRInvoice), InvApp, _
      Sheets("Invoice Spreadsheet").Range("H3:H" & LRInvoice), InvOrder) > 0 Then

    MatchTest = InvItem & InvOrder & InvBill & InvShip & InvApp

    'List Price
    Match = Application.WorksheetFunction.VLookup(MatchTest, InvoiceRng, 29, False)
    ActiveSheet.Range("I" & currentrow) = Match

    'Discount %
    Match = Application.WorksheetFunction.VLookup(MatchTest, InvoiceRng, 30, False)
    ActiveSheet.Range("K" & currentrow) = Match

    'Monthly Net
    Match = Application.WorksheetFunction.VLookup(MatchTest, InvoiceRng, 31, False)
    ActiveSheet.Range("L" & currentrow) = Match

    'Total Tax
    Match = Application.WorksheetFunction.VLookup(MatchTest, InvoiceRng, 32, False)
    ActiveSheet.Range("M" & currentrow) = Match

    'Total Amount
    Match = Application.WorksheetFunction.VLookup(MatchTest, InvoiceRng, 33, False)
    ActiveSheet.Range("N" & currentrow) = Match
End If

1 个答案:

答案 0 :(得分:1)

您可以跳过计数,而只需使用Match:

Set InvoiceRng = Sheets("Invoice Spreadsheet").Range("AB3:AG" & LRInvoice)

MatchTest = InvItem & InvOrder & InvBill & InvShip & InvApp

'do not use "worksheetfunction" - or will get run-time error if no match
m = Application.Match(MatchTest, InvoiceRng.Columns(1), 0) 'any match?
'test return value for error
If Not IsError(m) Then
    With ActiveSheet.Rows(currentrow)
        .Range("I1").Value = InvoiceRng.cells(m, 2).value
        .Range("k1").Value = InvoiceRng.cells(m, 3).value
        .Range("L1").Value = InvoiceRng.cells(m, 4).value
        .Range("M1").Value = InvoiceRng.cells(m, 5).value
        .Range("N1").Value = InvoiceRng.cells(m, 6).value
    End With
End If
相关问题