关于excel:VBA中的INDEX MATCH发出类型不匹配错误

INDEX MATCH in VBA issuing a type mismatch error

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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

要么

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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部分似乎正在引发错误。


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

你写了:

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

您没有完全合格所有Cells(),并且在Range("A1")Cells(1,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语句,因此更容易阅读:

1
2
3
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始终限定适当的范围。