VBA中的INDEX MATCH发出类型不匹配错误

时间:2019-06-28 13:48:25

标签: excel vba

在下面的代码中获得类型不匹配错误。目的是将布尔值返回到一个单元格,该布尔值是通过比较2个不同范围的2个输出的结果而得出的。一个范围只是一个直接range()函数,另一个范围是从INDEX MATCH中找到的结果。 MATCH函数给出错误,但我似乎无法弄清楚原因。

我在下面尝试了2种不同的选项。

dim i as long, j as long  
Dim index As Variant
Dim compare As Variant
Dim bool As Boolean  
i = 11
Do While i < RAGlastRow + 1
    j = 41
    Do While j < 44
        RAGspreadsheet.Cells(i, j) = Application.IsError(Application.Match(RAGspreadsheet.Range("C" & i).Value, HistoryWS.Range("C11", "C" & lastRow), 0))
        j = j + 1
        index = Application.index(HistoryWS.Range(Cells(11, 7).Address, Cells(lastRow, 7).Address), Application.Match(RAGspreadsheet.Range("C" & i).Value, HistoryWS.Range("C11", "C" & lastRow), 0))
        compare = RAGspreadsheet.Range("H" & i)
        bool = index <> compare
        RAGspreadsheet.Cells(i, j) = bool
        j = j + 1
        RAGspreadsheet.Cells(i, j) = RAGspreadsheet.Range("I" & i) <> Application.index(HistoryWS.Range(Cells(11, 8).Address, Cells(lastRow, 8).Address), Application.Match(RAGspreadsheet.Range("C" & i).Value, HistoryWS.Range("C11", "C" & lastRow), 0))
        j = j + 1
    Loop
    i = i + 1
Loop

dim i as long, j as long
i = 11
Do While i < RAGlastRow + 1
    j = 41
    Do While j < 44
        RAGspreadsheet.Cells(i, j) = Application.IsError(Application.Match(RAGspreadsheet.Range("C" & i).Value, HistoryWS.Range("C11", "C" & lastRow), 0))
        j = j + 1
        RAGspreadsheet.Cells(i, j) = RAGspreadsheet.Range("H" & i) <> Application.index(HistoryWS.Range(Cells(11, 7).Address, Cells(lastRow, 7).Address), Application.Match(RAGspreadsheet.Range("C" & i).Value, HistoryWS.Range("C11", "C" & lastRow), 0))
        j = j + 1
        RAGspreadsheet.Cells(i, j) = RAGspreadsheet.Range("I" & i) <> Application.index(HistoryWS.Range(Cells(11, 8).Address, Cells(lastRow, 8).Address), Application.Match(RAGspreadsheet.Range("C" & i).Value, HistoryWS.Range("C11", "C" & lastRow), 0))
        j = j + 1
    Loop
    i = i + 1
Loop

它的INDEX MATCH函数的MATCH部分似乎引发了错误。

1 个答案:

答案 0 :(得分:2)

解释我的评论。这适用于您的所有代码,尽管我将重点介绍index进行解释。

您写道:

index = Application.index(HistoryWS.Range(Cells(11, 7).Address, Cells(lastRow, 7).Address), Application.Match(RAGspreadsheet.Range("C" & i).Value, HistoryWS.Range("C11", "C" & lastRow), 0))

您没有完全合格所有Cells(),并且在Range("A1")Cells(1,1)之间来回交换,这很难保持一致。参见:

index = Application.index(HistoryWS.Range(HistoryWS.Cells(11, 7), HistoryWS.Cells(lastRow, 7)), Application.Match(RAGspreadsheet.Cells(i, 3).Value, HistoryWS.Range(HistoryWS.Cells(11, 3), HistoryWS.Cells(lastRow, 3)), 0))

我还从范围中删除了.Address


您也许应该使用With语句,这样更容易阅读:

With HistoryWS
    index = Application.index(.Range(.Cells(11, 7), .Cells(lastRow, 7)), Application.Match(RAGspreadsheet.Cells(i, 3).Value, .Range(.Cells(11, 3), .Cells(lastRow, 3)), 0))
End With

请注意,.会被保留,以使HistoryWS始终符合适当的范围。