Search code examples
excelvbaworksheet-function

VBA INDEX MATCH Run-time error '1004': Application-defined or object-defined error


I am getting a run-time error: "application-defined or object-defined error when I run the following code

    For i = 4 To lastOutputCol
        If (Sheets("Mort Rates").Cells(1, i).Value Mod 5) = 0 Then
            For x = 2 To numOutputRows

                With Sheets("Mort Rates")
                .Cells(x, i) = Application.WorksheetFunction.Index(Sheets("Input").Range(Sheets("Input").Cells(17, dbPerkCol), _
                Sheets("Input").Cells(lastInputRow, dbPerkCol + 2)), Application.WorksheetFunction.Match(.Cells(x, 2) & .Cells(1, i) & .Cells(x, 3), _
                Sheets("Input").Range(Sheets("Input").Cells(17, 1), Sheets("Input").Cells(lastInputRow, 1)), 0), 1)
                End With

            Next x
        End If
    Next i

The issue is with line

.Cells(x, i) = Application.WorksheetFunction.Index(Sheets("Input").Range(Sheets("Input").Cells(17, dbPerkCol), _
Sheets("Input").Cells(lastInputRow, dbPerkCol + 2)), Application.WorksheetFunction.Match(.Cells(x, 2) & .Cells(1, i) & .Cells(x, 3), _
Sheets("Input").Range(Sheets("Input").Cells(17, 1), Sheets("Input").Cells(lastInputRow, 1)), 0), 1)

I've checked and all of the variables used are correct.

EDIT:

I am trying to INDEX MATCH from an input sheet tables and return the correct value. I am now using this code:

    For i = 4 To lastOutputCol
        If (Sheets("Mort Rates").Cells(1, i).Value Mod 5) = 0 Then
            For x = 2 To numOutputRows

                With Sheets("Mort Rates")
                .Cells(x, i).Value = Application.WorksheetFunction.Index(Sheets("Input").Range(Sheets("Input").Cells(17, dbPerkCol), _
                Sheets("Input").Cells(lastInputRow, dbPerkCol + 2)), Application.WorksheetFunction.Match(.Cells(x, 2) & .Cells(1, i) & .Cells(x, 3), _
                Sheets("Input").Range(Sheets("Input").Cells(17, 1), Sheets("Input").Cells(lastInputRow, 1)), 0), 1)
                End With

            Next x
        End If
    Next i

The code works for a while(fills about half the cells I want) and then I get this error: "Unable to get the Mtch property of the WorksheetFunction class"


Solution

  • Dim ws as Worksheet
    set ws = ThisWorkbook.Worksheets("Input")
    For i = 4 To lastOutputCol
        If (Sheets("Mort Rates").Cells(1, i).Value Mod 5) = 0 Then
            For x = 2 To numOutputRows
    
                With ThisWorkbook.Sheets("Mort Rates")
                    .Cells(x, i).Value = Application.Index(ws.Range(ws.Cells(17, dbPerkCol), _
                    ws.Cells(lastInputRow, dbPerkCol + 2)), Application.Match(.Cells(x, 2) & .Cells(1, i) & .Cells(x, 3), _
                    ws.Range(ws.Cells(17, 1), ws.Cells(lastInputRow, 1)), 0), 1)
                End With
    
            Next x
        End If
    Next i