VBA索引匹配运行时错误'1004':应用程序定义或对象定义的错误

时间:2019-07-16 14:16:05

标签: excel vba worksheet-function

我收到运行时错误:“当我运行以下代码时,出现应用程序定义或对象定义的错误

    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

问题出在线路上

.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)

我已经检查过,所有使用的变量都是正确的。

编辑:

我正在尝试从输入工作表中索引匹配并返回正确的值。 我现在正在使用此代码:

    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

代码工作了一段时间(大约填满我想要的单元格的一半),然后出现此错误: “无法获取WorksheetFunction类的Mtch属性”

1 个答案:

答案 0 :(得分:1)

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