什么是索引和匹配VBA代码不起作用?

时间:2017-09-28 05:44:46

标签: excel excel-vba vba

我坚持使用这段代码,我一遍又一遍地看着,但我似乎无法找到问题。有谁知道它为什么会发出错误?错误的帖子如下所示。

For i = 2 To Total_rows_Pick
    For j = 2 To Total_rows_Dash
        If Application.WorksheetFunction.IfError(Application.WorksheetFunction.Index(Worksheets("Finished").Range("B2:B1048576"), Application.WorksheetFunction.Match(Worksheets("Pick-ups").Cells(i, 4), Worksheets("Finished").Range("A2:A1048576"), 0)), 1) <> 1 Then
            If Worksheets("Dashboard").Cells(j, 2) = Worksheets("Pick-ups").Cells(i, 2) And Worksheets("Pick-ups").Cells(i, 4) = Worksheets("Dashboard").Cells(j, 1) Then
                Worksheets("Dashboard").Cells(j, 3) = Worksheets("Dashboard").Cells(j, 3) + Worksheets("Pick-ups").Cells(i, 3)
            End If
        End If
    Next j
Next i

enter image description here

编辑(在尝试答案后):

enter image description here

修订代码(注意错误为第3行):

    For i = 2 To Total_rows_Pick
    For j = 2 To Total_rows_Dash
        m = Application.Match(Worksheets("Pick-ups").Cells(i, 4), Worksheets("Finished").Range("A2:A1048576"), 0)
        If Not IsError(m) Then
            If Application.WorksheetFunction.IfError(Application.WorksheetFunction.Index(Worksheets("Finished").Range("B2:B1048576"), Application.WorksheetFunction.Match(Worksheets("Pick-ups").Cells(i, 4), Worksheets("Finished").Range("A2:A1048576"), 0)), 1) <> 1 Then
                If Worksheets("Dashboard").Cells(j, 2) = Worksheets("Pick-ups").Cells(i, 2) And Worksheets("Pick-ups").Cells(i, 4) = Worksheets("Dashboard").Cells(j, 1) Then
                    Worksheets("Dashboard").Cells(j, 3) = Worksheets("Dashboard").Cells(j, 3) + Worksheets("Pick-ups").Cells(i, 3)
                End If
            End If
        End If
    Next j
Next i

1 个答案:

答案 0 :(得分:1)

如果没有匹配,那么Application.WorksheetFunction.Match会抛出一个运行时错误,就像您正在看到的那样(并且您可以使用{{1}进行陷阱})。如果您改为使用IfError(),那么它将返回一个错误值,您可以在使用索引中的返回值之前使用Application.Match进行测试:

IsError()